Application Level shortcut keys in WPF
Asked Answered
O

2

10

In WPF application I am currently trying to bind a Command to launch a calculator Tool form any where in the application using shortcut keys, I have created a command but not getting how to map commands and shortcut keys to create universal shortcut keys in my application. Thanks in advance.

Oleg answered 23/8, 2009 at 20:7 Comment(0)
A
9

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: Looks like you can't actually bind a KeyBinding to a ViewModel using just xaml if you're using MVVM: see here Keybinding a RelayCommand.

Ancestor answered 23/8, 2009 at 20:45 Comment(2)
Do you mean XAML rather than MXML? I think MXML is for Flex.Rheostat
Oops, yes I do! Too many technologies in my head! Fixed, thanks.Ancestor
P
4

In WPF in order to use shortcuts you need to focus the respective controller. However with InputManager you can capture all sorts of inputs of your application. Here you don't need to have focus on the respective controller.

First you have to subscrbe 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)
        {

        }
    }

Like this you can filter out all the unwanted stuff and get the required input. Since this is for a shortcut capturing application I only took the KeyDown and KeyUp event.

You can also get all the details of the key which is pressed

keyEvent.Key.ToString()
Postpositive answered 5/8, 2016 at 5:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.