且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实现键盘快捷键

更新时间:2022-10-18 10:50:25

您应该考虑实施 :

<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 和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.