简体   繁体   中英

KeyPress event doesn't trigger on WinForm UserControl

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 :)

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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