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 keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.
keypress Fires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed. keyup Fires when the user releases a key, after the default action of that key has been performed.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With