Difference between the KeyDown Event, KeyPress Event and KeyUp Event in Visual Studio
Can anyone tell me the difference between the KeyDown
event, the KeyPress
event and the KeyUp
event? I checked the msdn site and it does not explain it much.
Can anyone tell me in simple logical sense when each of the event occurs? I feel that all the above event occurs when a key is pressed. So what is the exact difference between them.
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.