我目前使用 onKeyDown
事件和 if/else
语句来创建键盘快捷键:
if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift && e.Key == Key.Tab) {
} else if (e.Key == Key.Tab) {
} ...
但是,如果我有更多的键盘快捷键,这会变得很困惑。
有没有更好的实现方式?
最佳答案
你应该看看实现 <CommandBindings>
和 <InputBindings>
:
<Window.CommandBindings>
<CommandBinding Command="Settings" CanExecute="SettingsCanExecute" Executed="SettingsExecuted" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="Settings" Key="S" Modifiers="Alt" />
</Window.InputBindings>
你的 <Button>
然后变成:
<Button Height="50" Width="50" Margin="50,5,0,0" Command="Settings" />
SettingsCanExecute
方法确定何时启用按钮和 SettingsExecuted
当按下按钮或敲击组合键时调用方法。
然后您就不需要 KeyDown
处理程序。
有一个 full tutorial打开代码。
有关 CommandBindings 的更多信息和 InputBindings可以在 MSDN 上找到。
关于c# - 实现键盘快捷键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3574405/