Domanda

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?

È stato utile?

Soluzione

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);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top