简体   繁体   English

在WinForm UserControl上不会触发KeyPress事件

[英]KeyPress event doesn't trigger on WinForm UserControl

I have a user control in my winforms application with this code in the KeyPress event: 我的winforms应用程序中有一个用户控件,其中包含KeyPress事件中的以下代码:

private void txtCodigo_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((this.txtCodigo.Text.Length == 0) && (e.KeyChar == '\r'))
    {
        this.Limpiar();
        if (LimpiarEvento != null)
            LimpiarEvento(this, new EventArgs());
        if (NextControl != null)
            NextControl(this, new EventArgs());
    }

    if ((this.txtCodigo.Text.Length > 0) && (e.KeyChar == '\r'))
        this.txtCodigo_Leave(sender, e);

    if (NUMEROS.IndexOf(e.KeyChar) < 0)
    {
        e.Handled = true;
    }
}

Now, my problem is that this UserControl is in many forms in my application and works perfectly when i press the enter key in the txtCodigo textbox but in one form the enter key is not being fired. 现在,我的问题是,该UserControl在我的应用程序中有多种形式,当我在txtCodigo文本框中按下Enter键时,它可以完美运行,但在一种形式中,不会触发Enter键。 Even if i put a breakpoint it doesn't fire at all. 即使我设置了断点,它也不会触发。 Why this could be happening? 为什么会发生这种情况?

Edit: I just try to add a KeyPress event to the form itself and set the KeyPreview to true and the Enter key is not being captured... all the other keys are being captured except the Enter key. 编辑:我只是尝试将一个KeyPress事件添加到窗体本身,并将KeyPreview设置为true并且没有捕获Enter键...除了Enter键之外,其他所有键均被捕获。 I really don't know what is happening. 我真的不知道发生了什么。 And yes... the enter key works fine in the keyboard :) 是的...回车键在键盘上可以正常工作:)

Does that particular form have its AcceptButton set? 该特定表单是否设置了AcceptButton?

(Already answered in comments) (已在评论中回答)

This SO question might be relevant for fixing up the Form: Prevent WinForm AcceptButton handling Return key 这个SO问题可能与修复表单有关: 防止WinForm AcceptButton处理返回键

Are you sure you added the event handler in the designer/code. 确定要在设计器/代码中添加事件处理程序吗? It can be done this way. 可以通过这种方式完成。 It should be added to the constructor where the control belongs. 应该将其添加到控件所属的构造函数中。

this.txtCodigo.KeyPress += new KeyPressHandler(txtCodigo_KeyPress);

EDIT: 编辑:

You are setting the event to be cancelled with this line of code. 您正在使用此代码行设置要取消的事件。

e.Handled = true;

Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.handled(v=vs.110).aspx 来源: http : //msdn.microsoft.com/zh-cn/library/system.windows.forms.keypresseventargs.handled(v=vs.110).aspx

What may be happening is this: 这可能是什么情况:

If you have copy-pasted the code from a previous program of yours the event handler hasn't be set. 如果您已经复制粘贴了您以前的程序中的代码,则不会设置事件处理程序。

First add the event handler from the designer of VS and inside the added handler paste your code. 首先,从VS设计器中添加事件处理程序,然后在添加的处理程序中粘贴您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM