Keyboard Events
Keyboard Events are ways we can design software to response to user input
through the keyboard. There aren't a lot of instances where we want to actively interfere while the
user types, but the few times we do, can provide a great deal of convenience and reduce headache.
For example, consider a text field where a user is expected to provide a phone number. By all the
old gods and the new ones, I certainly hope you don't expect the user to follow any particular
format when attempting this, as you both will likely be disappointed. Instead, use
Keyboard Events to "help" them complete the format.
For example, let's say you want to enforce the following template: (XXX) XXX-XXXX. You can use
Keyboard Events (1) to detect when the user begins to enter in a phone
number (based on which text field currently has "focus") (2) determine if the characters entered are
digits (and to reject any that are not) and (3) based on the number of digits they've entered,
automatically include the (, ), and - characters as necessary. "if
(phoneField.Text.Length == 4)", then its time to automatically append the closing parentheses
and padding space characters. This way, users can enter their phone numbers from a num pad (if their
keyboard has one) or at the very least, without including the non-digit characters, and you can
enforce a specific template. Everybody wins!
There are three Key events: KeyDown, KeyPress, and
KeyUp, relating to when you first push down a key, while the
key is being pressed, and finally the key being released. The KeyEventArgs
class has properties that can tell us more details about the key sequence being used (i.e. are you
typing 'a' or 'A'). Three boolean properties called Alt,
Control, and Shift, indicating whether these keys are a part of this
sequence. The Keys KeyCode identifies which key has been pressed by an
enumeration group, with members listed as Keyse.A and
Keys.PageDown, for example. Finally, there's a int KeyValue to
identify key codes by their ASCII value (which I personally think is silly to use if you can simply
code the target key codes by their typable character/phrase.)
There's also a KeyPressEventArgs class that contains a particularly useful
property, char KeyChar, which contains the value of the ASCII character
produced by the user's key sequence input.