-1

I have a form with some labels and two buttons, buttons are Yes and No.

For some reason I cannot get whether the user has pressed y or n keys on the form. If I use the same event for a textbox for example it works just fine.

private void Form2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Y)
            {
                btnYes.PerformClick();
            }
        }

Seems like that event never fires. Why is that?

sd_dracula
  • 3,796
  • 28
  • 87
  • 158
  • 1
    Why don't do a little bit of search before asking? See [results](https://www.google.co.uk/search?q=never+fires.&ie=utf-8&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&channel=rcs&gfe_rd=ctrl&ei=jMs6U4jqMYHY8geY-IHoAw&gws_rd=cr#channel=rcs&q=keydown+never+fires+c%23&rls=org.mozilla:en-US:official) – huMpty duMpty Apr 01 '14 at 14:22
  • 1
    btnYes.Text = "&Yes"; – Hans Passant Apr 01 '14 at 14:23

1 Answers1

3

Solution 1 : You need to set KeyPreview Property of the Form to true.

Try This:

this.KeyPreview = true;

Solution 2: But i would suggest you to override the ProcessCmdKey() method as below

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == Keys.Y) {
   btnYes.PerformClick();
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67