Difference between the KeyDown Event, KeyPress Event and KeyUp Event in Visual Studio
The MSDN documentation states the order in which the three events occur fairly clearly:
Key events occur in the following order:
- KeyDown
- KeyPress
- KeyUp
KeyDown
is raised as soon as the user presses a key on the keyboard, while they're still holding it down.
KeyPress
is raised for character keys (unlike KeyDown and KeyUp, which are also raised for noncharacter keys) while the key is pressed. This is a "higher-level" event than either KeyDown or KeyUp, and as such, different data is available in the EventArgs
.
KeyUp
is raised after the user releases a key on the keyboard.
Generally, you should handle the KeyUp
event in your application. Actions should not be initiated in the UI until after the user releases the key. And since KeyUp
is a lower-level event than KeyPress
, you'll always have plenty of information at your fingertips about the key that was pressed, and it will even work for handling non-character keys.
The thing to note about all of these events, however, is that they are only raised by the control that has the focus. That means if a button control on your form currently has the focus, none of the key events for your form will ever get raised. This is often confusing for programmers new to .NET. The best way to handle this is by overriding the form's ProcessCmdKey
method:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.A))
{
MessageBox.Show("You pressed Ctrl+A!");
}
return base.ProcessCmdKey(ref msg, keyData);
}
KeyDown: happens when the person presses a key (when the keyboard first detects a finger on a key, this happens when the key is pressed down).
KeyPress: happens when a key is pressed and then released.
KeyUp: happens when the key is released
You are right that all of these events occur when a key is pressed and then released, in the order I described above.
Here's a case when you DON'T want to use KeyUp:
You have a list box and pressing the Enter key on a row invokes an editor dialog. Problem: If the user presses the Enter key on the OK button of the editor, a KeyUp(e.KeyCode=Enter) event will leak back to your list box, causing the editor to reopen. This doesn't happen if the user presses the space bar on the editor's OK button; in that case the KeyUp(e.KeyCode=Space) event is handled by the editor before it closes.
Here's a selection heuristic I use:
If I'm handling the Enter key and I need to guard against a case like the one above
then I use KeyDown
Else if I'm handling key combinations (e.g. CTRL+C)
then I favor* KeyDown (KeyUp can make these awkward)
Else if I am allowing press & hold autorepeat
then I use KeyDown
Else
I use KeyUp
*If the action is a one that can be done in a commonly used product, say Microsoft Office, such as CTRL+A (for 'Select All'), then I mimic the Microsoft behavior, since that is what users are used to.