SoFunction
Updated on 2025-03-08

Share how WPF can monitor shortcut keys

1. Calling Win32 API

The highest priority is, global monitoring, support to minimize out-of-focus and other situations

So, if I want to listen to the CTRL+5 key in a WPF program, first add the following code to the main window program:

        /// <summary>
        /// CTRL+5 event Id        /// </summary>
        private const int Ctrl5KeyEventId = 9000;


        [DllImport("")]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("")]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);


        protected override void OnSourceInitialized(EventArgs e)
        {
            (e);

            var handle = new WindowInteropHelper(this).Handle;
            var source = (handle);
            source?.AddHook(HwndHook);
            //Real registration of shortcut key monitoring processing: Register CTRL+5 for numeric keys and keypad at the same time            RegisterHotKey(handle, Ctrl5KeyEventId, (uint), (uint)(Key.D5));
            RegisterHotKey(handle, Ctrl5KeyEventId, (uint), (uint)(Key.NumPad5));
        }


        private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            const int wmHotkey = 0x0312;

            switch (msg)
            {
                case wmHotkey:
                    switch (wParam.ToInt32())
                    {
                        case Ctrl5KeyEventId:
                            ("Win32 listens to CTRL+5 successfully");
                            break;
                    }
                    break;
            }

            return ;
        }


        protected override void OnClosing(CancelEventArgs e)
        {
            (e);

            var handle = new WindowInteropHelper(this).Handle;
            //Cancel registration after closing the window            UnregisterHotKey(handle, Ctrl5KeyEventId);
        }

2. Listen to WPF KeyDown event

Not halal enough, you can choose to minimize loss of focus and other monitoring failure

        public MainWindow()
        {
            InitializeComponent();
            KeyDown += MainWindow_KeyDown;
        }


        private void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if ( ==  && ( == Key.D5 ||  == Key.NumPad5))
            {
                ("WPF's KeyDown event listening to CTRL+5 successfully"); ;
                 = true;
            }
        }

Bind command method

Of course, WPF is preferred to select command binding, halal, minimize loss of focus and other monitoring failures.

The following is the XAML code for the main Window form

    <>
        <CommandBinding Command="{x:Static local:Commands.Ctrl5Command}" Executed="Ctrl5Command_OnExecuted"/>
    </>
    <>
        <KeyBinding Modifiers="Control" Key="D5"  Command="{x:Static  local:Commands.Ctrl5Command}" />
        <KeyBinding Modifiers="Control" Key="NumPad5"  Command="{x:Static  local:Commands.Ctrl5Command}" />
    </>

Executed method corresponding to the Window main form background code create command in the Executed command

        private void Ctrl5Command_OnExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            ("WPF's XAML binding command listens to CTRL+5 successfully");
        }

Added static classes related to commands:

    public static class Commands
    {
        public static ICommand Ctrl5Command { get; } = new RoutedCommand();
    }

4. Details

Priority of three monitoring schemes

Where Win32 > XAML binding command = KeyDown event, if you listen at the same time, only high priority will be handled. In the above example, if

I listen to three at the same time and can only handle win32

Win32 listens to CTRL+5 successfully

Global monitoring problem

Among them, win32 supports global monitoring of keyboards, that is, windows can be monitored in case of out-of-focus, such as minimization, and the XAML binding command and KeyDown event do not support out-of-focus, and minimization, etc. will not be monitored. Therefore, you must select the solution according to the business.

DEMO link

The above is the detailed content shared by WPF to implement monitoring shortcut keys. For more information about WPF monitoring shortcut keys, please pay attention to my other related articles!