Detect Arrow Key - KeyDown for the whole window

2020-02-01 01:51发布

I have a WinForms Form (C#/.Net) and it contains a PictureBox, MenuStrip, Panel and two Button controls.

I need to detect KeyDown event for the Arrow Keys for the whole window; i.e., when the window is in the foreground, regardless of which one of the child controls has the focus, I need to know when an arrow key is pressed and execute some code when it happens.

I don't want to go and attach an event handler for each control. Is there a better way? How can I do it?

Edit: Using KeyPreview as suggested by an answer below, I am able to detect other keys. Not able to detect arrow keys. I am able to detect arrow keys only when the buttons in my form are disabled. Or else, they take up focus back and forth and don't fire the event. How can I detect arrow keys with buttons on the form?

2条回答
Melony?
2楼-- · 2020-02-01 01:57

Override the ProcessCmdKey() method to detect the arrow keys.

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (keyData == Keys.Left) {
            Console.WriteLine("left");
            return true;
        }
        // etc..
        return base.ProcessCmdKey(ref msg, keyData);
    }
查看更多
何必那么认真
3楼-- · 2020-02-01 01:58

You have to set the KeyPreview property to true in the Form

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx

With this the key-related events will be fired in the Form before they are fired in the focused control.

查看更多
登录 后发表回答