Most Windows Forms applications process keyboard input exclusively by handling the keyboard events. You can detect most physical key presses by handling the KeyDown or KeyUp events. Key events occur in the following order:
KeyDown KeyPress KeyUp
In most cases, the standard KeyUp, KeyDown, and KeyPress events are enough to catch and handle keystrokes. However, not all controls raise these events for all keystrokes under all conditions. For example. The KeyPress event is raised for character keys while the key is pressed and then released. But This event is not raised by noncharacter keys, unlike KeyDown and KeyUp, which are also raised for noncharacter keys
In order to capture keystrokes in a Forms control, you must derive a new class that is based on the class of the control that you want, and you override the ProcessCmdKey().
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
//handle your keys here
}
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean 'handle your keys here End Function
This ProcessCmdKey is called during message preprocessing to handle command keys, also it is called only when the control is hosted in a Windows Forms application or as an ActiveX control.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
//capture up arrow key
if (keyData == Keys.Up )
{
MessageBox.Show("You pressed Up arrow key");
return true;
}
//capture down arrow key
if (keyData == Keys.Down )
{
MessageBox.Show("You pressed Down arrow key");
return true;
}
//capture left arrow key
if (keyData == Keys.Left)
{
MessageBox.Show("You pressed Left arrow key");
return true;
}
//capture right arrow key
if (keyData == Keys.Right )
{
MessageBox.Show("You pressed Right arrow key");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
'detect up arrow key
If keyData = Keys.Up Then
MessageBox.Show("You pressed Up arrow key")
Return True
End If
'detect down arrow key
If keyData = Keys.Down Then
MessageBox.Show("You pressed Down arrow key")
Return True
End If
'detect left arrow key
If keyData = Keys.Left Then
MessageBox.Show("You pressed Left arrow key")
Return True
End If
'detect right arrow key
If keyData = Keys.Right Then
MessageBox.Show("You pressed Right arrow key")
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
NEXT.....Enum with Switch.Case