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.
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.
keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key. keyup – fires when any key is released, fires last, and the browser processes the key.
The keydown event is triggered first when user presses a key. The keyup event is triggered last when user releases a key. In between, the keypress event is triggered.
There is apparently a lot of misunderstanding about this!
The only practical difference between KeyDown
and KeyPress
is that KeyPress
relays the character resulting from a keypress, and is only called if there is one.
In other words, if you press A on your keyboard, you'll get this sequence of events:
But if you press Shift+A, you'll get:
If you hold down the keys for a while, you'll get something like:
Notice that KeyPress
occurs in between KeyDown
and KeyUp
, not after KeyUp
, as many of the other answers have stated, that KeyPress
is not called when a character isn't generated, and that KeyDown
is repeated while the key is held down, also contrary to many of the other answers.
Examples of keys that do not directly result in calls to KeyPress
:
Examples of keys that do result in calls to KeyPress
:
For the curious, KeyDown
roughly correlates to WM_KEYDOWN
, KeyPress
to WM_CHAR
, and KeyUp
to WM_KEYUP
. WM_KEYDOWN
can be called fewer than the the number of key repeats, but it sends a repeat count, which, IIRC, WinForms uses to generate exactly one KeyDown per repeat.
The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.
https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress
KeyPress is only fired by printable characters and is fired after the KeyDown event. Depending on the typing delay settings there can be multiple KeyDown and KeyPress events but only one KeyUp event.
KeyDown
KeyPress
KeyUp
KeyPress is a higher level of abstraction than KeyDown (and KeyUp). KeyDown and KeyUp are hardware related: the actual action of a key on the keyboard. KeyPress is more "I received a character from the keyboard".
Keydown is pressing the key without releasing it, Keypress is a complete press-and-release cycle.
Put another way, KeyDown + KeyUp = Keypress
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