3 events occurred during the keyboard press key and then released, respectively, for the KeyDown event, the KeyPress event, and the KeyUp event. The KeyDown and KeyUp events let the application capture the special keys or some specific keys or even key combinations that the user presses on the keyboard, and only use the KeyDown and KeyUp events when they want to get information about the key or special key. The following KeyDown and KeyUp events are described separately.
1. KeyDown events
The KeyDown event occurs the first time a key is pressed.
Example KeyDown use of events
In this example, you determine whether the user presses a special key and, if so, it appears on the title bar of the form.
The main program code is as follows.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string G_str_Mode = "";
string G_str_text = e.KeyCode + ":" + e.Modifiers + ":" + e.KeyData + ":" + "(" + e.KeyValue + ")";
if (e.Shift == true)
G_str_Mode = "Shift 键被按下";
if (e.Control == true)
G_str_Mode = "Ctrl 键被按下";
if (e.Alt == true)
G_str_Mode = "Alt 键被按下";
this.Text = G_str_text + G_str_Mode;
}
Note: In the above code, the KeyDown event takes a KeyEventArgs object E and returns the relevant key information, and the KeyEventArgs parameter provides several property values, which return the corresponding value according to the pressed key on the keyboard. The property values for the KeyEventArgs parameter are shown in the table.
Table KeyEventArgs Property value
|
description |
control |
|
keycode |
get KeyDown or the keyboard code for the KeyUp event |
|
keydata |
get key data for KeyDown or KeyUp events |
keyvalue |
Gets the keyboard value of the KeyDown or KeyUp event |
get modifier flags for KeyDown or KeyUp events. These flags indicate the combination of the CTRL, SHIFT, and ALT keys that are pressed |
shift |
|
2. KeyUp events
The KeyUp event occurs when a key is released.
Example KeyUp use of events
This example sets the size of the form automatically when the program is run and the keyboard is pressed.
The main program code is as follows.
private void frmKeyDownUP_KeyUp(object sender, KeyEventArgs e)
{
this.ClientSize = new System.Drawing.Size(800,100);
}