Pressing of a key is detected and handled in Windows Form using KeyPress, KeyDown or similar events.
this.KeyDown += myForm_KeyDown; private void myForm_KeyDown(object sender, KeyEventArgs e) { //Your code here }
But these events does not fire when arrow keys are pressed. One way to get around it is to set KeyPreview
as true for your Form. In many cases, this also doesn’t work, for instance, when you have buttons on your Form.
In such cases, ProcessCmdKey can be overridden to detect and handle arrow key events.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { switch(keyData) { case Keys.Down: //Handle down arrow key event break; case Keys.Up: //Handle up arrow key event break; case Keys.Right: //Handle right arrow key event break; case Keys.Left: //Handle left arrow key event break; } return base.ProcessCmdKey(ref msg, keyData); }
After handling the arrow key event if you do not want the standard arrow key functionality to kick in, return true
rather than calling return base.ProcessCmdKey(ref msg, keyData);
Standard functionality could be to move focus to the next or previous control.
Returning true from ProcessCmdKey
means event has been handled and should not be routed further for processing.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
//handle your keys here
}
Full example..Detecting arrow keys in c#
evan