【问题标题】:Application Level shortcut keys in WPFWPF 中的应用程序级快捷键
【发布时间】:2010-11-22 02:37:55
【问题描述】:

在 WPF 应用程序中,我目前正在尝试绑定命令以使用快捷键在应用程序中的任何位置启动计算器工具,我已经创建了一个命令,但没有了解如何映射命令和快捷键以创建通用快捷键我的应用程序。 提前致谢。

【问题讨论】:

    标签: .net wpf windows keyboard-shortcuts commandbinding


    【解决方案1】:

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

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

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

    【讨论】:

    • 您的意思是 XAML 而不是 MXML?我认为 MXML 适合 Flex。
    • 糟糕,我愿意!我脑子里的技术太多了!已修复,谢谢。
    【解决方案2】:

    在 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 2010-11-24
      • 2010-10-05
      • 2012-08-10
      • 2017-03-28
      • 2016-04-21
      • 1970-01-01
      相关资源
      最近更新 更多