14.12 Keyboard-Event Handling

Key events occur when keyboard keys are pressed and released. Such events can be handled for any control that inherits from System.Windows.Forms.Control. There are three key events—KeyPress, KeyUp and KeyDown. The KeyPress event occurs when the user presses a character key or the space or backspace keys. The specific key can be determined with property KeyChar of the event handler’s KeyPressEventArgs argument.

The KeyPress event does not indicate whether modifier keys (e.g., Shift, Alt and Ctrl) were pressed when a key event occurred. If this information is important, the KeyUp or Key-Down events can be used. The KeyEventArgs argument for each of these events contains information about modifier keys. Figure 14.39 lists important key event information. Several properties return values from the Keys enumeration, which provides constants that specify the various keys on a keyboard. Like the FontStyle enumeration (Section 14.7), the Keys enumeration is represented with a set of bits, so the enumeration’s constants can be combined with the bitwise operators to indicate multiple keys pressed at the same time.

Fig. 14.39 Keyboard events and event arguments.

Keyboard events and event arguments
Key Events with Event Arguments of Type KeyEventArgs
KeyDown Generated when a key is initially pressed.
KeyUp Generated when a key is released.
Key Event with Event Argument of Type KeyPressEventArgs
KeyPress Generated when a key is pressed. Raised after KeyDown and before KeyUp.
Class KeyPressEventArgs Properties
KeyChar Returns the ASCII character for the key pressed.
Class KeyEventArgs Properties
Alt Indicates whether the Alt key was pressed.
Control Indicates whether the Ctrl key was pressed.
Shift Indicates whether the Shift key was pressed.
KeyCode Returns the key code for the key as a value from the Keys enumeration. This does not include modifier-key information. It’s used to test for a specific key.
KeyData Returns the key code for a key combined with modifier information as a Keys value. This property contains all information about the pressed key.
KeyValue Returns the key code as an int, rather than as a value from the Keys enumeration. This property is used to obtain a numeric representation of the pressed key. The int value is known as a Windows virtual key code.
Modifiers Returns a Keys value indicating any pressed modifier keys (Alt, Ctrl and Shift). This property is used to determine modifier-key information only.

Figure 14.40 demonstrates the use of the key-event handlers to display a key pressed by a user. The program is a Form with two Labels that displays the pressed key on one Label and modifier key information on the other.

Fig. 14.40 Displaying information about the key the user pressed.

Alternate View

  1    // Fig. 14.40: KeyDemo.cs
  2    // Displaying information about the key the user pressed.
  3    using System;
  4    using System.Windows.Forms;
  5
  6    namespace KeyDemo
  7    {
  8        // Form to display key information when key is pressed
  9        public partial class KeyDemo : Form
 10        {
 11            // default constructor
 12            public KeyDemo()
 13            {
 14               InitializeComponent();
 15            }
 16
 17            // display the character pressed using KeyChar
 18            private void KeyDemo_KeyPress(object sender, KeyPressEventArgs e)
 19            {
 20               charLabel.Text = $"Key pressed: {e.KeyChar}";
 21            }
 22
 23            // display modifier keys, key code, key data and key value
 24            private void KeyDemo_KeyDown(object sender, KeyEventArgs e)
 25            {
 26               keyInfoLabel.Text =
 27                  $"Alt: {(e.Alt ? "Yes" : "No")}
" +
 28                  $"Shift: {(e.Shift ? "Yes" : "No")}
" +
 29                  $"Ctrl: {(e.Control ? "Yes" : "No")}
" +
 30                  $"KeyCode: {e.KeyCode}
" +
 31                  $"KeyData: {e.KeyData}
" +
 32                  $"KeyValue: {e.KeyValue}";
 33            }
 34
 35            // clear Labels when key released
 36            private void KeyDemo_KeyUp(object sender, KeyEventArgs e)
 37            {
 38               charLabel.Text = "";
 39               keyInfoLabel.Text = "";
 40            }
 41        }
 42    }

Control charLabel displays the character value of the key pressed, whereas keyInfo-Label displays information relating to the pressed key. Because the KeyDown and KeyPress events convey different information, the Form (KeyDemo) handles both.

The KeyPress event handler (lines 18–21) accesses the KeyChar property of the KeyPressEventArgs object. This returns the pressed key as a char, which we then display in charLabel (line 20). If the pressed key is not an ASCII character, then the KeyPress event will not occur, and charLabel will not display any text. ASCII is a common encoding format for letters, numbers, punctuation marks and other characters. It does not support keys such as the function keys (like F1) or the modifier keys (Alt, Ctrl and Shift).

The KeyDown event handler (lines 24–33) displays information from its KeyEventArgs object. The handler tests for the Alt, Shift and Ctrl keys using the Alt, Shift and Control properties that each return a booltrue if the corresponding key is pressed and false otherwise. The handler then displays the KeyCode, KeyData and KeyValue properties.

The KeyCode property returns a Keys enumeration value (line 30). The KeyCode property returns the pressed key, but does not provide any information about modifier keys. Thus, both a capital and a lowercase “a” are represented as the A key.

The KeyData property (line 31) also returns a Keys enumeration value, but also includes modifier-key data. Thus, if “A” is input, the KeyData shows that both A and Shift were pressed. Lastly, KeyValue (line 32) returns an int representing a pressed key. This int is the key code. The key code is useful when testing for non-ASCII keys like F12.

The KeyUp event handler (lines 36–40) clears both Labels when the key is released. As we can see from the output, non-ASCII keys are not displayed in charLabel, because the KeyPress event is not generated. For example, charLabel does not display any text when you press the F7 key, as shown in Fig. 14.40(b). However, the KeyDown event still is generated, and keyInfoLabel displays information about the key that’s pressed. The Keys enumeration can be used to test for specific keys by comparing the KeyCode of the pressed key to values in the Keys enumeration.

Software Engineering Observation 14.2

To cause a control to react when a particular key is pressed (such as Enter), handle a key event and test for the pressed key. To cause a Button to be clicked when the Enter key is pressed on a Form, set the Form’s AcceptButton property.

By default, a keyboard event is handled by the control that currently has the focus. Sometimes it’s appropriate to have the Form handle these events. This can be accomplished by setting the Form’s KeyPreview property to true, which makes the Form receive keyboard events before they’re passed to another control—for example, a key press would raise the Form’s KeyPress, even if a control within the Form has the focus instead of the Form itself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset