【问题标题】:How can i trigger a event when a keyboard shortcut ( Ctrl+F7 ) is fired?触发键盘快捷键( Ctrl+F7 )时如何触发事件?
【发布时间】:2019-12-30 17:57:03
【问题描述】:

我想在我的应用程序中有人使用快捷键 Ctrl+F7 时获取事件。因为我的应用程序中有设置,我不希望任何人能够更改,但如果他必须更改这些设置,我可以为他提供键盘快捷键。

当触发 CTRL+F7 时,我的应用程序如何知道(当快捷方式被触发时,应用程序具有焦点。)

【问题讨论】:

    标签: wpf vb.net keyboard-shortcuts


    【解决方案1】:

    您可以覆盖主窗口的OnPreviewKeyDown 方法:

    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        base.OnPreviewKeyDown(e);
        if (e.Key == Key.F7 && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.LeftCtrl)))
        {
            //...
        }
    }
    

    如果您的应用程序有多个顶级窗口,您可以创建一个通用基类,在其中覆盖该方法,然后从该基类继承您的所有窗口:

    public abstract class AppWindow : Window
    {
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            base.OnPreviewKeyDown(e);
            if (e.Key == Key.F7 && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.LeftCtrl)))
            {
                //...
            }
        }
    }
    
    public partial class MainWindow : AppWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    

    XAML:

    <local:AppWindow x:Class="WpfApp1.MainWindow">...</local:AppWindow>
    

    【讨论】:

      【解决方案2】:

      您可以像这样使用带有热键的命令绑定:

      <Window.CommandBindings>
          <CommandBinding Command="{x:Static local:CustomCommands.ShortCutCommand}" Executed="CommandBinding_Executed_1"  CanExecute="CommandBinding_CanExecute" />
      </Window.CommandBindings>
      <Window.InputBindings>
          <KeyBinding Command="{x:Static local:CustomCommands.ShortCutCommand}" Key="F7" Modifiers="Ctrl" />
      </Window.InputBindings>
      

      MainWindow.cs

      public static RoutedCommand ShortCutCommand= new RoutedCommand();
      private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
      {
          e.CanExecute = true;
      }
      
      private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e)
      {
          //do something here
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-22
        • 2011-03-22
        • 2013-01-24
        相关资源
        最近更新 更多