Question

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.

Was it helpful?

Solution

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;

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top