Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Manning - Windows.forms.programming.with.c#.pdf
Скачиваний:
108
Добавлен:
12.02.2016
Размер:
14.98 Mб
Скачать

12.1KEYBOARD EVENTS

We looked briefly at keyboard events in chapter 9 while discussing the TextBox class. There we used the KeyPress event to limit what characters could appear in a text box control. In this section we look more generically at keyboard events, and use them in our application to provide some quick shortcuts for the user.

There are three distinct events that occur whenever a key is pressed and released. Note that we did not say whenever a character is pressed and released. A character may involve multiple key presses. For example, the letter ‘A’ requires the use of the Shift key and the A key, typically abbreviated as Shift+A (of course, this is not true if the Caps Lock key is pressed, but you understand).

The three keyboard events are summarized in the following table. These events occur for a control in the order shown in the table whenever the control has the focus.

Keyboard events

Event

Description

Event Argument

 

 

 

KeyDown

Occurs when a key on the keyboard is pressed

KeyEventArgs class

 

down.

 

KeyPress

Occurs when a character is pressed on the

KeyPressEventArgs class

 

keyboard, and again each time the character is

 

 

repeated while it continues to be pressed.

 

KeyUp

Occurs when a key on the keyboard is released.

KeyEventArgs class

 

 

 

12.1.1HANDLING THE KEYPRESS EVENT

The KeyPress event is used for generic handling of keyboard characters. Event handlers of this type receive an instance of the KeyPressEventArgs class as its event parameter. See .NET Table 12.1 for an overview of this class.

.NET Table 12.1 KeyPressEventArgs class

The KeyPressEventArgs class is the event argument class associated with the KeyPress event. This class represents the keyboard character pressed by the user. It is part of the System.Windows.Forms namespace, and inherits from the System.EventArgs class.

Handled

Public Properties

KeyChar

Gets or sets whether the keyboard character was handled. If true, then the control will not receive the character.

Gets the char value corresponding to the keyboard character pressed.

It is important to realize that this event, as well as the KeyDown and KeyUp events, is received by the control that currently has the focus. In particular, they are not normally received by parent controls such as Panel and Form objects that contain the control. Normally this is a good thing. The per-character behavior is defined by each control, with no need for parental involvement. For example, if you are handling the

384

CHAPTER 12 A .NET ASSORTMENT

KeyPress event to force a text box to contain only integer values, you do not want to spend precious operating system cycles percolating this event up through the set of containing objects for the text box. A parent control such as a Panel or GroupBox will only receive a keyboard event if it specifically has the focus.

This presents a slight problem for subclasses of the ContainerControl object, and in particular the Form object. As you may recall, a ContainerControl object manages the focus for the contained controls, and does not receive the focus directly. There are plenty of situations where you would like to initiate an action from the keyboard regardless of the current control.

The good folks at Microsoft created the KeyPreview property in the Form class for just this purpose. When this property is set to true, the Form object will receive all keyboard events before they are passed to the current control. If the event handler sets the Handled property to true, then the current control will not receive the keyboard key or corresponding character.

Let’s create an example of this in our MyPhotos program by handling the plus ‘+’ and minus ‘–’ characters. The plus character will display the next photograph in the album, while the minus will display the previous photograph. We would like these to occur at the Form level, and not just in our Panel object where the image is displayed. The following table presents the steps required for this change.

Set the version number of the MyPhotos application to 12.1.

MAP THE PLUS AND MINUS KEYS TO THE NEXT AND PREVIOUS MENUS

 

Action

Result

 

 

 

1

In the MainForm.cs [Design] window,

 

 

modify the KeyPreview property for the

 

 

MainForm object to be true.

 

 

 

 

2

Override the protected OnKeyPress

protected override void OnKeyPress

 

method in the MainForm.cs source file.

(KeyPressEventArgs e)

 

 

{

 

 

 

3

When a plus sign ‘+’ is pressed, invoke

switch (e.KeyChar)

 

the Next menu handler.

{

 

 

case '+':

 

 

e.Handled = true;

 

 

menuNext.PerformClick();

 

 

break;

 

 

 

4

When a minus sign ‘-’ is pressed, invoke

case '-':

 

the Previous menu handler.

e.Handled = true;

 

 

menuPrevious.PerformClick();

 

 

break;

 

 

 

5

For all other characters, do nothing. This

default: // do nothing

 

permits the character to be sent to child

break;

 

controls.

}

 

 

 

 

 

6

Don’t forget to call the base class at the

base.OnKeyPress(e);

 

end of the method.

}

 

 

 

KEYBOARD EVENTS

385

We could have used an if statement in this code, especially with only two items to check. Since we may add behavior for additional characters in the future, a switch statement seems like a good idea. Note how we used the MenuItem.PerformClick method to simulate a user click of the appropriate menu. We could have called the Click event handler directly, of course, but this solution is a bit more elegant.

It should be noted here that not all characters are received by the KeyPress and other keyboard events. Depending on the control, some characters may be preprocessed and unavailable by default in this event. The protected IsInputKey and IsInputChar methods can be used to determine whether a specific character is preprocessed in a derived control.

Let’s move on to the KeyDown and KeyUp events.

12.1.2HANDLING OTHER KEYBOARD EVENTS

The KeyDown and KeyUp events are useful to fine-tune an application’s behavior as keyboard keys are pressed and released, and for handling noncharacter keys such as the function or arrow keys. Handlers for these events receive an instance of the

KeyEventArgs class as their event parameter. This class is summarized in .NET Table 12.2.

.NET Table 12.2 KeyEventArgs class

The KeyEventArgs class is the event argument class associated with the KeyDown and KeyUp events. This class represents the keyboard key pressed down or released by the user. It is part of the System.Windows.Forms namespace, and inherits from the System.EventArgs class.

 

Alt

Gets whether the Alt key was pressed.

 

Control

Gets whether the Ctrl key was pressed.

 

Handled

Gets or sets whether the event was handled.

 

KeyCode

Gets the specific keyboard key pressed as a value in the Keys

 

 

enumeration.

Public

KeyData

Gets the combination of keyboard keys pressed at the same

Properties

 

time using the Keys enumeration values.

 

KeyValue

Gets the int character value corresponding to the keyboard

 

 

combination.

 

Modifiers

Gets the combination of modifier keys pressed or released

 

 

using the Keys enumeration values. This is a combination of the

 

 

Ctrl, Shift, and Alt values, or None if no keys were pressed.

 

Shift

Gets whether the Shift key was pressed.

 

 

 

We will demonstrate the use of the KeyEventArgs class by setting the Page Up and Page Down keys to invoke the Previous and Next menus, respectively. We will use the KeyDown event for this purpose. We have already set the KeyPreview property to receive keyboard events in our Form, so all we have to do is override the OnKeyDown method here.

386

CHAPTER 12 A .NET ASSORTMENT

Соседние файлы в папке c#