Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
362 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...