Difference between the KeyDown Event, KeyPress Event and KeyUp Event in Visual Studio

68,477

Solution 1

  • 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.

Solution 2

The MSDN documentation states the order in which the three events occur fairly clearly:

Key events occur in the following order:

  1. KeyDown
  2. KeyPress
  3. 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);
}

Solution 3

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.

Solution 4

In addition to the other answers:

When trying to figure to which of these events you should hookup your action, mind that the KeyDown event will be fired multiple times while the key is held down. Sometimes you want this behavior, sometimes not. Based on that I suggest the following usage (based on my experience):

(Order in which events are fired)

KeyDown

Occurs: When key is pressed and while held down
Usage: Perform action immediately on button press or even multiple times when held down
Example: Moving cursor with arrow keys

.

KeyPress

Occurs: Character key is pressed (Higher level event)
Usage: Anything typing related
Example: Handle textbox input

.

KeyUp

Occurs: Key is released
Usage: Perform critical action which should only occur once per keystroke
Example: Write data to file

Solution 5

KeyDown then KeyPress then KeyUp is the order I find.

Usually you want to hook KeyDown when it is for an application where a user holds down a key for multi-mode input with control key mode modification, like in a shift-click operation. KeyPress is for simple key entry type logic -- just getting the key strokes. KeyUp is hooked to put in logic that executes after something else processes KeyPress, like to modify the contents of a text edit box after it's main KeyPress logic has taken effect. Frankly, I don't use KeyUp all that much, but sometimes it is the only way to get a message after something else has processed KeyPress and you need to check on / fixup what happened.

Share:
68,477
reggie
Author by

reggie

Application Specialist at Intergraph

Updated on July 05, 2022

Comments

  • reggie
    reggie almost 2 years

    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.

  • B. Clay Shannon-B. Crow Raven
    B. Clay Shannon-B. Crow Raven almost 12 years
    I wonder how easy that info is to find? It seems to me it would be helpful if there was a site with a chart showing the order of event occurrences for each native Windows control...
  • weberc2
    weberc2 over 11 years
    Or perhaps some sort of information aggregation site with a question-answer format to make said information easily accessible? Going to the original documentation isn't always the ideal solution...
  • Jim C
    Jim C over 11 years
    Even though reggie didn't ask this, I added an answer below with thoughts on when to use KeyDown vs KeyUp.
  • Cody Gray
    Cody Gray about 11 years
    @Clay They don't have such a chart because the order of events/messages is (generally speaking) subject to change at any time. It's an implementation detail of the underlying control, so you can't rely on a particular order for all available messages. But some particular messages are always sent in a particular order simply because of their design and what they mean. For example, the ones I've called out here. The WinForms documentation does have a pretty good explanation of this for the key-related events, I think.
  • O'Rooney
    O'Rooney over 10 years
    Very helpful thoughts Jim. But, doesn't this result in an inconsistent experience? That could be argued shouldn't happen, because the dialog should not be acting until the key up event. Up to now, I have always used KeyUp (for Enter key) to be consistent, but I ran into your state problem.
  • Sabuncu
    Sabuncu almost 10 years
    +1 Such a complete answer, a model answer for providing useful information.
  • Sabuncu
    Sabuncu almost 10 years
    In WPF, the "leaking" of the Enter key can be prevented by handling it in a by a Preview event, right?
  • Juan
    Juan about 9 years
    The KeyPress description is wrong. KeyPress occurs while the key is pressed, even if is never released. See Cody Gray's answer.
  • Dave Cousineau
    Dave Cousineau almost 8 years
    If you handle KeyUp, you don't get repeats if the user holds the key down. Also it's not correct to say that something should only happen when you release a key. That is true for clicking buttons, but not pressing keys.
  • bmadtiger
    bmadtiger over 7 years
    You can get a form to respond to key events normally handled by controls on the form if you set the form's KeyPreview (msdn.microsoft.com/en-us/library/…) property to true.
  • Cody Gray
    Cody Gray about 5 years
    @Max: You should call the base class implementation: return base.ProcessCmdKey(ref msg, keyData);
  • Jess
    Jess over 4 years
    Thanks -- I could not catch "Alt-F4" in KeyUp… had to use KeyDown.
  • ourmandave
    ourmandave over 3 years
    And KeyPress only fires once. KeyDown fires continuous if the key is held down.