KeyPress event doesn't trigger on WinForm UserControl

99封情书 提交于 2019-12-14 03:15:31

问题


I have a user control in my winforms application with this code in the KeyPress event:

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. 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. I really don't know what is happening. And yes... the enter key works fine in the keyboard :)


回答1:


Does that particular form have its AcceptButton set?

(Already answered in comments)

This SO question might be relevant for fixing up the Form: Prevent WinForm AcceptButton handling Return key




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/23430109/keypress-event-doesnt-trigger-on-winform-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!