0

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

Phoenix_uy
  • 3,173
  • 9
  • 53
  • 100

3 Answers3

3

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

Community
  • 1
  • 1
MicroVirus
  • 5,324
  • 2
  • 28
  • 53
0

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

markieo
  • 484
  • 3
  • 14
  • Yes, the event handler is there... and with other keys the event is fired... this is only happening with the Enter Key and only that form. In other forms the UserControl works perfectly – Phoenix_uy May 02 '14 at 14:16
  • Yeah... i'm cancelling the event with the `e.Handled = true` but inside the event.. and if i press the enter key this doesn't even fire the event – Phoenix_uy May 02 '14 at 14:24
0

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.

apomene
  • 14,282
  • 9
  • 46
  • 72
  • The code was not copy-pasted and the event handler is capturing all the keys except enter key only in this form.. in the other forms works perfectly. – Phoenix_uy May 02 '14 at 14:17