9

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.

4

2 回答 2

7

您可以在 xaml 中执行此操作 - 请参阅KeyBinding类的文档中的示例:

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

更新:如果您使用 MVVM,您似乎不能仅使用 xaml 将 KeyBinding 绑定到 ViewModel:请参见此处Keybinding a RelayCommand

于 2009-08-23T20:45:01.163 回答
4

在 WPF 中,为了使用快捷方式,您需要关注相应的控制器。但是使用 InputManager,您可以捕获应用程序的各种输入。在这里,您无需关注相应的控制器。

首先,您必须订阅该事件。

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

然后,

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)
        {

        }
    }

像这样,您可以过滤掉所有不需要的东西并获得所需的输入。由于这是一个快捷方式捕获应用程序,我只使用了 KeyDown 和 KeyUp 事件。

您还可以获得按下的键的所有详细信息

keyEvent.Key.ToString()
于 2016-08-05T05:19:13.473 回答