Keyboard Event Handling



To handle KeyPress events:

(1) in Form1.Designer.cs, place the following:

this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(Form1_KeyPress);

(2) in Form1.cs, place the  following delegate immediately after the form's constructor:

public delegate void KeyPressEventHandler(object sender, KeyPressEventArgs e);

(3) in Form1.cs, add the following method:

private void Form1_KeyPress(object sender, KeyPressEventArgs e) {
            MessageBox.Show("A key was pressed.");
        }

--------------------------------------------------------------------------------

To handle KeyDown events:

(1) in Form1.Designer.cs, place the following:

this.KeyDown += new System.Windows.Forms.KeyEventHandler(Form1_KeyDown);

(2) in Form1.cs,  place the following immediately after the form's constructor:

public delegate void KeyEventHandler(object sender, KeyEventArgs e);

(3) in Form1.cs, add  the following method:

       private void Form1_KeyDown(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                MessageBox.Show("Enter key pressed.");
            }
            if (e.KeyCode == Keys.Escape) {
                MessageBox.Show("Escape key pressed.");
            }
        }


--------------------------------------------------------------------------------


To handle KeyUp events:

(1) in Form1.Designer.cs, place the following:

this.KeyUp+= new System.Windows.Forms.KeyEventHandler(Form1_KeyUp);

(2) in Form1.cs, place the following immediately after the form's constructor:

public delegate void KeyEventHandler(object sender, KeyEventArgs e);

(3) in Form1.cs, add the following method:

Key KeyDown KeyUp KeyPress
Tab yes no yes
Shift yes no no
Caps yes no no
Esc yes no yes
F1 to F12 yes no no
Ctrl yes no no
WinKey yes no no
Alt yes no no
Space yes no yes
AppsKey yes no no
Enter yes no yes
Back yes no yes
arrow keys yes no no
PrintScreen no yes no
Scroll yes no no
Pause yes no no
Insert yes no no
Home yes no no
PageUp yes no no
Delete yes no no
End yes no no
Next (i.e., PageDown yes no no
NumLock yes no no

The numeric keypad behaves one way when the NumLock is on, and another when it is off. When the numeric keyboard is locked into numbers mode, pressing one of the numeral keys will trigger both a KeyPress and a KeyDown event. However, when not locked into numbers mode, i.e., when the "4" key means Left, and the "3" key means Next, etc., only a KeyDown event is triggered, and each key's alternate meaning is applies. For instance, "7" is Home, "1" is End, and "0" is Insert.