实现键盘快捷键 [英] Implement Keyboard Shortcuts
问题描述
我目前使用 onKeyDown
事件和 if/else
语句来创建键盘快捷键:
if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift && e.Key == Key.Tab) {} else if (e.Key == Key.Tab) {} ...
但是,如果我有更多的键盘快捷键,这会变得很混乱.
有更好的实现吗?
<CommandBinding Command="Settings" CanExecute="SettingsCanExecute" Executed="SettingsExecuted"/></Window.CommandBindings><Window.InputBindings><KeyBinding Command="Settings" Key="S" Modifiers="Alt"/></Window.InputBindings>
你的 然后变成:
SettingsCanExecute
方法确定按钮何时被启用,SettingsExecuted
方法在按钮被按下或组合键被敲击时被调用.
然后您就不需要 KeyDown
处理程序.
有一个关于 Switch 的完整教程在代码上.
有关CommandBindings 和<的更多信息可以在 MSDN 上找到 href="http://msdn.microsoft.com/en-us/library/system.windows.input.inputbinding.aspx" rel="noreferrer">InputBindings.>
I currently use the onKeyDown
event and an if/else
statement to create keyboard shortcuts:
if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift && e.Key == Key.Tab) {
} else if (e.Key == Key.Tab) {
} ...
However, if I have quite a few more keyboard shortcuts, this gets messy.
Is there a better implementation?
You should look at implementing <CommandBindings>
and <InputBindings>
:
<Window.CommandBindings>
<CommandBinding Command="Settings" CanExecute="SettingsCanExecute" Executed="SettingsExecuted" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="Settings" Key="S" Modifiers="Alt" />
</Window.InputBindings>
Your <Button>
then becomes:
<Button Height="50" Width="50" Margin="50,5,0,0" Command="Settings" />
The SettingsCanExecute
method determines when the button is enabled and the SettingsExecuted
method is called when the button is pressed or the key combination struck.
You then don't need the KeyDown
handler.
There's a full tutorial on Switch On The Code.
More information on CommandBindings and InputBindings can be found on the MSDN.
这篇关于实现键盘快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!