What is the difference between the KeyDown
and KeyPress
events in .NET?
This question is related to
.net
Easiest explanation:
I held down the 'd' key for a second and then released.
dddddd
the keydown event happened once before the first d appeared on the screen, the keypress event happened 6 times and the keyup event happened after the last d appeared on the screen.
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
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
I've always thought keydown happened as soon as you press the key down, keypress is the action of pressing the key and releasing it.
I found this which gives a little different explanation: http://bytes.com/topic/net/answers/649131-difference-keypress-keydown-event
KEYUP will be captured only once, upon release of the key pressed, regardless of how long will the key be held down, so if you want to capture such press only once, KEYUP is the suitable event to capture.
From Blogging Developer:
In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.
Note: You can also try out the Key Event Tester (available on the above-mentioned site) to understand this concept.
Keydown is pressing the key without releasing it, Keypress is a complete press-and-release cycle.
Put another way, KeyDown + KeyUp = Keypress
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".
Source: Stackoverflow.com