简体   繁体   中英

Keydown Event not firing

Trying to fire up an event when a button is pressed on the keyboard. Ive set the Form1 property to have the KeyPreview to True as well. But still, its not firing and i cant see whats wrong.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Modifiers == Keys.A)
    MessageBox.Show("A pressed");
    else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.F1)
    MessageBox.Show("Combination of ALt and F1 pressed");
}

try with KeyCode:

if (e.KeyCode==Keys.A)
                MessageBox.Show("A pressed");
            ...

Also keep in mind that Form1 must have the focus when you press the corresponding button

Set the KeyPreview property of the form to true.

Otherwise the child controls will catch the event first.

setting the event

this.KeyDown += Form5_KeyDown;
this.KeyPreview = true;

the event

void Form5_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
        MessageBox.Show("A pressed");
    else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.F1)
        MessageBox.Show("Combination of ALt and F1 pressed");
}

dont forget the KeyPreview = true , if you want to handle all keydown

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM