0

I have a windows form that has bunch of controls. Whenever any key is clicked, like arrow keys, I want to raise an event. The problem isn't in code, the problem is that the controls have a tab index so anytime I click on arrow keys the cursor just moves to another control and that's what I don't want.

squillman
  • 13,363
  • 3
  • 41
  • 60
R.Vector
  • 1,669
  • 9
  • 33
  • 41

3 Answers3

2

Attach each controls KeyDown event to the same handler:

 Control.KeyDown+=new KeyEventHandler(Control_KeyDown);

 private void Control_KeyDown(object sender, KeyEventArgs e)
 {
        //trap here and handle
        if(e.KeyCode == Keys.Left || e.KeyCode == Keys.Right || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
            e.Handled = true;
 }
devHead
  • 794
  • 1
  • 15
  • 38
  • this will completely seize the function of Arrow Keys, imagine you are one a TextBox control and the Arrow are not working to change cursor position within TextBox – Parimal Raj Jan 25 '13 at 22:05
  • Agreed, there would need to be a procedure that tested for an edit control and handle accordingly… – devHead Jan 26 '13 at 01:43
2

You have to be sure that there isn't any active control on the current form. Put this code in Form.cs

this.ActiveControl = null;
Nick
  • 4,192
  • 1
  • 19
  • 30
2

After some testing i found out

    protected override bool ProcessDialogKey(Keys keyData)
    {
        return false;
    }

This will cause the arrow keys (and tab) to be delivered as normal KeyDown events. This will also cause the normal dialogue key functionality (For e.g. Tab & Arrow keys) to stop, but still get the KeyDown event

Parimal Raj
  • 20,189
  • 9
  • 73
  • 110