Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...