0

I would need that (on a WinForm) if the key A is pressed, an event is triggered. I got this code from the MSDN site:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode != Keys.A)
     {
          MessageBox.Show("Key 'a' was pressed.");
     }
}

The problem is that this code doesn't work for me, there is no error message, but if I am on the form and press the key A there is no event triggered. I tried to use breakpoints, but it never enters the if.

What is the problem here?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Ian H.
  • 3,840
  • 4
  • 30
  • 60
  • Well, for one, you have `!=`, which means is looking for a key that's *not* `Keys.A`. Also, you probably still have to add this function to the form's keydown event (you can use the designer). – nanny Nov 19 '15 at 14:07

1 Answers1

2

You need to set Form.KeyPreview property to True. This property gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

Also note that there is a mistake in your code; according to your message you need to verify if e.KeyCode == Keys.A.

tezzo
  • 10,858
  • 1
  • 25
  • 48