简体   繁体   中英

Get keydown event without a textbox

Im trying to do like that: If I press the key "P" a messagebox will open in the screen.But I need to do it without a textbox or other tool, I want to do that direct in the form.

I tried:

private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.P)
        { MessageBox.Show("Key P pressed"); }
    }

Try with the KeyPress Event of the form. It just works fine.

在此处输入图片说明

在此处输入图片说明

Assuming this is Winforms, on the form you're trying to catch the event on, make sure to set

Form1.KeyPreview = true;

KeyPreview ensures that keyboard events anywhere on the particular form (such as to a textbox with focus) will still count as a keyboard event for the form itself.

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