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.
Asked
Active
Viewed 1,744 times
0
-
1capture the event in the form itself and set KeyPreview to false. – Federico Berasategui Jan 25 '13 at 21:41
-
2@HighCore - must be set to true, by default it is false – Parimal Raj Jan 25 '13 at 21:41
-
1@AppDeveloper That's what I meant. I have not used dinosaur winforms in a loong while. – Federico Berasategui Jan 25 '13 at 21:43
-
1@HighCore - he he happens! – Parimal Raj Jan 25 '13 at 21:46
-
1http://stackoverflow.com/a/14530877/922198 – Parimal Raj Jan 25 '13 at 21:46
-
1@R.Vector - ans updated,do check it for sure! – Parimal Raj Jan 25 '13 at 22:02
-
Thanks everybody for the great help, i fixed it because of your suggestions and solutions. – R.Vector Jan 25 '13 at 22:21
3 Answers
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
-
That piece of code solved the whole issue, of course i had to add this.KeyPreview = true; – R.Vector Jan 25 '13 at 22:12
-
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