Detect Arrow Key - KeyDown for the whole window

吃可爱长大的小学妹 提交于 2019-11-26 21:16:21

问题


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?


回答1:


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);
    }



回答2:


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.



来源:https://stackoverflow.com/questions/4378865/detect-arrow-key-keydown-for-the-whole-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!