Detect Arrow Key - KeyDown for the whole window

user529141 picture user529141 · Dec 7, 2010 · Viewed 8.2k times · Source

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?

Answer

Hans Passant picture Hans Passant · Dec 7, 2010

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