Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top