techno
techno

Reputation: 6500

Capturing Enter Key press on windows form not working

I have a user authentication form with username and password textboxes.There is an okay button that fires the code to validate the credentials. I want the same code to get executed when the user hits Enter key anywhere on the form. So i register for the keypress event like this

 this.KeyPress += UserLogin_KeyPress;
 private void UserLogin_KeyPress(object sender, KeyPressEventArgs e)
        {
             if (e.KeyChar == (char)13)
                {
                MessageBox.Show("enter");
                }

        }

This event is not triggered at all.What i'm i doing wrong?

Upvotes: 2

Views: 4317

Answers (4)

Dave Cousineau
Dave Cousineau

Reputation: 13158

As mentioned, set form.KeyPreview = true so that most key events will be given to the form before the controls.

However, note that this doesn't always work, and some controls will still "steal" certain key presses anyway. For example, if a Button has focus, then an Enter keypress will be used by the button to activate it, before you get a chance to see it, and since it counts as having been "handled", you never get to see the keypress.

The workaround I use for this is to set focus to something that I know will not steal the enter key press, for key presses that occur leading up to the enter key press. So, if the pressed keys are <1><2><3><4><ENTER> then the 1-4 keys all set focus to something that is not a button (usually, the textbox where I am displaying the resulting text), and then when <ENTER> is pressed, it should make it to your form's event handler (as long as KeyPreview == true).

Upvotes: 1

Geraldo Diaz
Geraldo Diaz

Reputation: 356

Try setting the property keypreview to true and changing to keydown instead since KeyPress don't support e.Keycode:

private void UserLogin_KeyPress(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            MessageBox.Show("Enter");
        }
    }

Upvotes: 3

Joel Coehoorn
Joel Coehoorn

Reputation: 415755

It's only looking at the form. Controls on the form also need to be wired in.

Upvotes: 0

ksdev
ksdev

Reputation: 56

Try this:

private void UserLogin_KeyPress(object sender, KeyPressEventArgs e)
{
   if (e.KeyCode == Keys.Enter)
   {
      MessageBox.Show("enter");
   }
}

Upvotes: 1

Related Questions