WPF shortcut keys (form)

Original: WPF Shortcut Keys (form)

Foreword: In the development of the WPF project, I encountered the need to use shortcut keys, so I did a quick study on hot keys, but there are few resources in this area. . .


 Hotkeys are roughly divided into three scenarios. The following uses QQ as an example:

Global hotkey: QQ Ctrl + Alt + A screenshot .

Focus hotkey: Shift + Enter text in the QQ message bar.

Window hotkey: Alt + F4 to close the QQ window.

 

In WPF among global hotkeys and focus hotkeys can be easily achieved , I am only following form hotkeys to explain.

The first step: Right project root directory references -> Management Nuget Package -> Search NHotkey.Wpf and download and install

It is recommended to add the registration command to Window (the hot key needs to be triggered after the mouse clicks the focus in Page and UserControl ). Without further ado, see the code:

XAML中:

Copy code
    < Window.Resources > 
        < RoutedUICommand x: Key = "WinKeyDown" Text = "F1"  /> 
        <!- WinKeyDown is a static resource name, F1 is a synonym for your hotkey (as you like) used for background reception- > 
    </ Window.Resources > 
    < Window.InputBindings > 
        < KeyBinding Gesture = "F1" Command = " {StaticResource WinKeyDown} " HotkeyManager.RegisterGlobalHotkey = "True" /> 
        <!- F1 is the hotkey on the keyboard, the core property of HotkeyManager .RegisterGlobalHotkey = "true" Join to trigger the hotkey without focus, and the global hotkey will not happen- > 
    </Window.InputBindings>
    <Window.CommandBindings>
        <CommandBinding Command="{StaticResource WinKeyDown}"
                   CanExecute="CommandBinding_CanExecute"/>
        <!--CanExecute触发事件-->
    </Window.CommandBindings>
Copy code

Background code:

Copy code
        //窗体热键
        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            switch (((System.Windows.Input.RoutedUICommand)e.Command).Text) 
            {
                case "F1":
                    MessageBox.Show("deep dark fantasy");
                    break;
                default:
                    return;
            }
        }
Copy code

That's it, now even if your application does not have focus, the hotkey bound command will be called.

You can achieve subconscious operations such as Ctrl + S save and F5 refresh.

Please forward the link to indicate the source.

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12730277.html