WPF Check if Key is Pressed


We have a small demo program in Windows Presentation Foundation (WPF) that shows how you might check if the user has pressed a keyboard key while using your program. Please feel free to use the C# or XAML code listed below. You can create your own program and have it on hand as an example. I’ve called my project KeyboardTrapping. It’s not much to look at, but the code behind could be useful in your project.

Below is the screenshot of the program. Click on it to enlarge it.

WPF Check if Key is Pressed

Below is the XAML code. There are a few items to take note of if you are a XAML beginner. WindowStartupLocation=”CenterScreen”, PreviewKeyDown=”Window_PreviewKeyDown”, Button Name=”btnRightArrow” Click=”btnRightArrow_Click”, and TextBox Name=”txtbox” KeyDown=”OnKeyDownHandler”.

<Window x:Class="KeyboardTrapping.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:KeyboardTrapping"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        PreviewKeyDown="Window_PreviewKeyDown"
        Title="Keyboard Trapping Demo" Height="280" Width="400" MinHeight="280" MinWidth="400">
    <StackPanel Margin="10">
        <TextBlock FontSize="20" Margin="10" HorizontalAlignment="Center" Foreground="Blue">Keyboard Trapping Demo</TextBlock>
        <TextBlock TextWrapping="Wrap" Margin="10">Pressing certain keyboad keys will reveal popup messages. 
            Try the right or left arrows, A or a, the space bar, the F2 key, the number 7,
            Ctrl+G, Crtl+g, Ctrl+T or Ctrl+t.</TextBlock>
        <Button Name="btnRightArrow" Click="btnRightArrow_Click" Margin="10">Right Arrow</Button>
        <TextBlock Name="txtblk" Width="300" Height="20">
            Type in the TextBox below and press the Enter key.
        </TextBlock>
        <TextBox Name="txtbox" KeyDown="OnKeyDownHandler" Margin="10" ></TextBox>
    </StackPanel>
</Window>

The most interesting part of this post is the C# code behind. The Window_PreviewKeyDown() function is for the entire application. As long as the application has the focus, this function will be called. To achieve this, we must have PreviewKeyDown=”Window_PreviewKeyDown” in the XAML. Even if the user is working inside the text box at the bottom of the application, and the for example presses the A key, the Window_PreviewKeyDown() will fire and a message will pop up. If the user presses Ctrl+G then they receive a popup. If the user just presses the Ctrl key and releases the Ctrl key, nothing happens (that the user can see).

using System.Windows;
using System.Windows.Input;

namespace KeyboardTrapping
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                if (e.Key == Key.G) MessageBox.Show("Ctrl+G or Ctrl+g", "Keyboard Trapping Demo");
                if (e.Key == Key.T) MessageBox.Show("Ctrl+T or Ctrl+t", "Keyboard Trapping Demo");
            }
            if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt))
            {
                if (e.Key == Key.G) MessageBox.Show("Alt+G or Alt+g", "Keyboard Trapping Demo");
                if (e.Key == Key.T) MessageBox.Show("Alt+T or Alt+t", "Keyboard Trapping Demo");
            }
            // ... Test for right or left arrow keys and equate those to
            // clicking the right or left arrow buttons.
            // do not forget PreviewKeyDown="Window_PreviewKeyDown" in the XAML.
            if (e.Key == Key.Right) btnRightArrow_Click(sender, e);
            if (e.Key == Key.Left) MessageBox.Show("left arrow key", "Keyboard Trapping Demo");
            // test for other keys
            if (e.Key == Key.A) MessageBox.Show("A or a", "Keyboard Trapping Demo");
            if (e.Key == Key.F2) MessageBox.Show("F2", "Keyboard Trapping Demo");
            if (e.Key == Key.D7) MessageBox.Show("7", "Keyboard Trapping Demo");
            if (e.Key == Key.Space) MessageBox.Show("Space", "Keyboard Trapping Demo");
        }
        private void btnRightArrow_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("You clicked the right arrow button or the right arrow key. " +
                "Thanks for your patronage. Please come again.", "Keyboard Trapping Demo");
        }
        private void OnKeyDownHandler(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                txtblk.Text = "You Entered: " + txtbox.Text;
            }
        }
    }
}