views:

638

answers:

3

Hi everybody, I'm new around here and i have a little problems with a C# application. I want to capture the key down event. This wasn't a problem at first but after i added some buttons to the form, the key down event of the form ignores the arrow keys and moves the focus from one button to the next.(The key up event works) Is there a way to stop this and make them do something else when i hold the arrow keys?

+1  A: 

Set the KeyPreview property on the Form to true. That will allow the form to see the keydown event in addition to the child controls.

Add this to your Form ...

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData.Equals(Keys.Right))
    {
        MessageBox.Show("Right Key Pressed!");
    }

    return base.ProcessCmdKey(ref msg, keyData);
}
JP Alioto
I had the KeyPreview set to true but still don't get any response when the arrow keys are pressed. All other keys seem to be working in the KeyDown event except the arrows.
sheitan
The normal Form Key* events do not caputre the control keys. You need to override ProcessCmdKey instead.
JP Alioto
Thank you very much. This helped me a lot! :)
sheitan
+1  A: 

If you don't want the normal key down functionality for the controls you will need to set the key down event on each control, and set the handled attribute for the event arguments to be true, that way it doesn't bubble up to the built in control functionality.

Sebastian Bender
A: 

I've tried a simple test... An empty form with just a simple KeyDown event:


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

...and it worked. I added a button and copied the same code to his KeyDown, and added the handled part.

private void button1_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
if (e.KeyCode == Keys.Right)
MessageBox.Show("Right");
}

The MessageBox doesn't appear anymore... The KeyPreview of the form is set to true... what am i missing?

sheitan
You should reply with a comment to one of the above answers, or editing or commenting your question, thx
Maghis