First, keyboard classes and keyboard events
WPF provides the underlying keyboard class (System.Input.Keyboard Class), which provides keyboard-related events, methods, and properties that provide information about the state of the keyboard. Keyboard events are also provided externally through events in XAML base element classes such as UIElement.
For keyboard operations, there are two groups of commonly used events:
KeyDown events and Previewkeydown events: Handling keyboard Keys Press
KeyUp events and Previewkeyup events: Handling Keyboard keys Lifting
Where the KeyDown and KeyUp events belong to the bubbling routed event, and Previewkeydown and Previewkeyup belong to the tunneling routed event.
In order for the element to receive keyboard input, the element must have the focus. By default, most UIElement derived objects can have focus. If this is not the case, set the Focusable property on the base element to true if you want the element to have the focus. Panel classes like StackPanel and Canvas set the default value of Focusable to false. Therefore, the focusable must be set to true for these objects to get the keyboard focus.
For example: In the author's notebook have "mute", "Increase volume", "reduce volume" These three shortcuts, in an application of the form to handle the three key clicks can:
1: <window x:class= "Inputcommandandfocus.window1"
2:xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation& quot;
3:xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"
4:title= "Window1" height= "480" width= "
5:focusable= "True" previewkeydown= "Window_previewkeydown" >
6: <Canvas>
7: <!--...-->
8: </Canvas>
9: </Window>
1:private void Window_previewkeydown (object sender, KeyEventArgs e)
2: {
3:if (E.key = = Key.volumemute)
4: {
5://Press "mute" key
6:txtmessage.text = "Mute";
7:e.handled = true;
8:}
9:else if (E.key = = key.volumeup)
10: {
11://Press "Increase volume" key
12:txtmessage.text = "Up";
13:e.handled = true;
14:}
15:else if (E.key = = Key.volumedown)
16: {
17://Press the "Reduce volume" button
18:txtmessage.text = "Down";
19:e.handled = true;
20:}
21:}