Application-level shortcuts in WPF

In a WPF application, I'm currently trying to link a command to run a calculator. Shape the tool anywhere in the application using keyboard shortcuts. I created a command, but I don’t get how to match commands and keyboard shortcuts to create universal keyboard shortcuts in my expression. Thanks in advance.

+6
windows wpf keyboard-shortcuts commandbinding
source share
3 answers

CommandManager wants to use focused control as a starting point for routing all input bindings.

I wrote Behavior, which makes it easy to bind global keyboard shortcuts for any control using RoutedCommand (standard WPF) and ICommand (MVVM style).

WPF Behavior: Global Shortcut Keys for Applications

+7
source share

You can do this in xaml - see the example in the documentation for the KeyBinding class:

<Window.InputBindings> <KeyBinding Command="ApplicationCommands.Open" Gesture="CTRL+R" /> </Window.InputBindings> 

Update. It looks like you cannot bind KeyBinding to ViewModel using only xaml if you use MVVM: see here Keybinding RelayCommand .

+5
source share

In WPF, to use shortcuts, you need to focus the appropriate controller. However, with the InputManager you can capture all kinds of inputs from your application. Here you do not need to focus on the appropriate controller.

First you need to sign the event.

 InputManager.Current.PreProcessInput -= Current_PreProcessInput; InputManager.Current.PreProcessInput += Current_PreProcessInput; 

Then

 private void Current_PreProcessInput(object sender, PreProcessInputEventArgs args) { try { if (args != null && args.StagingItem != null && args.StagingItem.Input != null) { InputEventArgs inputEvent = args.StagingItem.Input; if (inputEvent is KeyboardEventArgs) { KeyboardEventArgs k = inputEvent as KeyboardEventArgs; RoutedEvent r = k.RoutedEvent; KeyEventArgs keyEvent = k as KeyEventArgs; if (r == Keyboard.KeyDownEvent) { } if (r == Keyboard.KeyUpEvent) { } } } } catch (Exception ex) { } } 

Similarly, you can filter out all unnecessary things and get the required input. Since this is a shortcut capture app, I used the KeyDown event and KeyUp event.

You can also get all the details of a keystroke.

 keyEvent.Key.ToString() 
+3
source share

All Articles