There are three key events:
This event is raised once when a user presses a key.
The second argument of the event handler is of type KeyEventsArgs.
This event is raised when the key or keys pressed result in a character. For instance, "Shift" plus "a" produces the character "A".
If the keys are held down, the KeyPress event may be generated repeated, as in "AAAAAAAAA".
The second argument of the event handler is of type KeyPressEventsArgs.
This event is raised when a key is released.
The second argument of the event handler is of type KeyEventsArgs.
Thus the sequence of events is: KeyDOwn, KeyPress, KeyUp.
In the Designer file, we need a line to attach the handler to the event:
this.KeyDown +=
new System.Windows.Forms.KeyEventHandler(this.KeyDemo_KeyDown);
KeyEventArgs class
This is found in the System.Windows.Forms namespace and has various properties, some of which are:
This is true if the Alt key was pressed, false otherwise.
This is true if the Control key was pressed, false otherwise.
This is true if the Shift key was pressed, false otherwise.
This gives us the key code for the key as a member of the Keys enumeration. It does not include modifier-key information.
The Keys enumeration has many members corresponding to the many keys on the standard keyboard (and some others). We can refer, for instance to Keys.A, Keys.PageDown, Keys.PrintScreen, Keys.RControlKey, Keys.F1, etc. These all have corresponding integer values; the values for printable characters match those in the ASCII sequence, so Keys.A has the value 65.
This is the integer value for the key.
KeyPressEventsArgs
This has properties. The most useful is:
char KeyChar
which gives the ASCII character produced by the key or keys pressed.