【问题标题】:WPF shortcut with ALT带有 ALT 的 WPF 快捷方式
【发布时间】:2016-12-22 07:43:51
【问题描述】:

我需要一个问题。我想在 Window 中捕获 alt 代码(ALT + 64 = @)。我的代码对于使用 Control 的快捷方式是正确的,但是当我更改为 ALT 时,它不起作用,并且 Key 属性中的值是“System”。这是我的代码:

正确:

if (e.Key == Key.S && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)//CTRL+S

错误:

 if (e.Key == Key.S 
  && (Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) //ALT+S dont work - e.Key="System"

我的第二个问题是如何模拟 ALT+64(多键)。顶级示例仅适用于 ALT+6

谢谢

【问题讨论】:

    标签: wpf


    【解决方案1】:

    由于您使用的是 WPF,因此处理键盘快捷键的最佳方式是通过 InputGesture

      /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }      
    
            private void ExitCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
            {
                e.CanExecute = true;
            }
    
            private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
            {
                Console.WriteLine("Your implementation");
            }
    
        }
    
    
        public static class CustomCommands
        {
            public static readonly RoutedUICommand Exit = new RoutedUICommand
                    (
                            "Exit",
                            "Exit",
                            typeof(CustomCommands),
                            new InputGestureCollection()
                                    {
                                            new KeyGesture(Key.S, ModifierKeys.Alt)
                                    }
                    );
    
            //Define more commands here, just like the one above
        }
    

    将此添加到 xaml

    <Window.CommandBindings>
            <CommandBinding Command="self:CustomCommands.Exit" CanExecute="ExitCommand_CanExecute" Executed="ExitCommand_Executed" />
        </Window.CommandBindings>
    

    【讨论】:

      【解决方案2】:

      试试这个:

      if( e.KeyboardDevice.Modifiers == ModifierKeys.Alt && e.SystemKey == Key.S )
      

      【讨论】:

      • 这没问题,但我想按下这个快捷键:ALT+53 这是数字 5 的 ascii 代码
      • 由于数字不是有效的枚举键,微软在您的案例中将数字键命名为“DX”(“Key.D5”)。
      • Key.D5 是带有数字 5 的数字键,您可以在“T”键上方找到它,或者在小键盘上的其他数字的中心,并且您在第一次询问评论这个答案。您可以简单地将我的答案中的“Key.S”替换为“Key.D5”
      猜你喜欢
      • 2011-01-17
      • 2014-11-20
      • 2018-07-17
      • 1970-01-01
      • 2011-11-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多