KeyDown. Applications sometimes need to access keyboard commands. With the KeyDown event handler (in C# code) we can listen for key presses, like "function keys" like F5 for example.
Getting started. Let us begin with a new WPF program. Please add a KeyDown event handler to the Window element. Let Visual Studio create Window_KeyDown by pressing Enter.
Example code. Here we add some code to the event handler. In the Window_KeyDown method, the KeyEventArgs is important. From it, we access the key that was pressed.
Info Key is the property that tells us what key was pressed. In this example, we test against the Key.F5 constant.
Tip When the user presses F5, the window title will change to a special message. In many programs, like web browsers, F5 means "reload."
<Window x:Class="WpfApplication25.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
KeyDown="Window_KeyDown">
</Window>using System.Windows;
using System.Windows.Input;
namespace WpfApplication25
{
/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
// ... Test for F5 key.
if (e.Key == Key.F5)
{
this.Title = "You pressed F5";
}
}
}
}
KeyBinding. More complicated key presses are handled with "gestures" in WPF. We can specify commands with KeyBinding elements. On MenuItems, we can specify InputGestureText.
And With a simple KeyDown method, we cannot easily handle complex commands. A KeyBinding is needed.
Summary. With KeyDown, we add keyboard commands to WPF programs. We used the Key property to test a KeyEventsArg object. For complex keyboard requirements, KeyBindings are needed.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.