BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Base Classes - UIElement - Keyboard Events

The twenty-first part of the Windows Presentation Foundation Fundamentals tutorial continues the investigation of the base classes of the WPF layout controls. This article describes the keyboard events provided by the UIElement type.

Determining the Pressed Key

In most cases checking for any key being pressed is insufficient; you will want to know which key was used. This information is provided by the event arguments, within the Key property. The property returns a value from the Key enumeration, which has named constants defined for all of the keys on a standard keyboard.

Let's modify the event code so that it only detects presses of the R, Y, G and B keys and changes the background colour of the window to red, yellow, green or blue accordingly. Change the event code as follows:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.Key)
    {
        case Key.R: Background = Brushes.Red; break;
        case Key.Y: Background = Brushes.Yellow; break;
        case Key.G: Background = Brushes.Green; break;
        case Key.B: Background = Brushes.Blue; break;
    }
}

Try running the program again and pressing some keys. You should find that the four keys detected by the switch statement change the window's colour but all other keys have no effect.

Routed Events

KeyDown is a routed event. A routed event can be raised by one control but handled by another, usually one that is an ancestor of the originating control. In the example, when you press a key whilst one of the text boxes or buttons has the focus, it is that control that raises the event. The event then bubbles up the object tree where it can be caught by an event handler on the grid or the window.

When a routed event is raised, it is quite possible that it will be handled at several levels in the logical tree. We can demonstrate this by adding a second KeyDown event. This time we'll attach it to the FirstName text box. Start by modifying this control's XAML as follows:

<TextBox Name="FirstName" Grid.Column="1" Margin="6" KeyDown="FirstName_KeyDown"/>

Now add the code. This is similar to that for the window but uses different shades for the four colours.

private void FirstName_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.Key)
    {
        case Key.R: FirstName.Background = Brushes.Tomato; break;
        case Key.Y: FirstName.Background = Brushes.LightYellow; break;
        case Key.G: FirstName.Background = Brushes.LightGreen; break;
        case Key.B: FirstName.Background = Brushes.LightBlue; break;
    }
}

Try running the program again. This time click the FirstName text box to give it the focus before pressing R, Y, G and B. You will see that both of our event methods are called by the event, causing the text box and window backgrounds to change. This is the routed event in action, first being called by the text box before bubbling up the logical tree and being handled by the window too.

Preventing Routing of Keyboard Events

Sometimes you will want to prevent a KeyDown event from being bubbled up the object tree. You may decide that if one of the text boxes can process a key press or key combination that the window should no longer react to the event. You control this with the event arguments. The KeyEventArgs class includes a Boolean property named Handled. If you set the value to true, no further event methods will be called.

Let's demonstrate this. Add the following line of code to the end of the FirstName_KeyDown method, just before the closing brace character ({). This will set the Handled flag after changing the text box's background colour. Setting the flag indicates that the window should not process the event.

Try running the program and pressing the R, Y, G and B keys whilst the FirstName text box has the focus and when it does not. With the TextBox selected only its background will change in response to the KeyDown event. With any other control focussed the window background is updated.

e.Handled = true;

KeyUp Event

The second keyboard event supplied by UIElement is KeyUp. This event is virtually identical in operation to KeyDown. The difference is that the event is raised when a pressed key is released.

To demonstrate, add the event to the Window's XAML element, as follows:

<Window x:Class="UIElementDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="UI ElementDemo"
        Width="250"
        Height="150"
        KeyDown="Window_KeyDown"
        KeyUp="Window_KeyUp">

In the code we'll set the window's background colour to white when a key is released.

private void Window_KeyUp(object sender, KeyEventArgs e)
{
    Background = Brushes.White;
}

Try running the program to see the event in action. Make sure that the FirstName text box is not focussed when you press the keys.

16 July 2013