![](/img/trans.png)
[英]Best way to implement keyboard shortcuts in a Windows Forms application?
[英]Implement Keyboard Shortcuts
我目前使用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
處理程序。
有關Switch On The Code的完整教程 。
有關CommandBindings和InputBindings的更多信息可以在MSDN上找到。
為其他人記錄這個答案,因為有一個很簡單的方法來做這個很少被引用,並且根本不需要觸摸XAML。
要鏈接鍵盤快捷鍵,只需在Window構造函數中添加一個新的KeyBinding到InputBindings集合。 作為命令,傳入實現ICommand的任意命令類。 對於execute方法,只需實現您需要的任何邏輯。 在下面的示例中,我的WindowCommand類接受一個委托,它將在每次調用時執行。 當我構造新的WindowCommand以傳入我的綁定時,我只是在我的初始化程序中指出我希望WindowCommand執行的方法。
您可以使用此模式來提供自己的快捷鍵盤快捷鍵。
public YourWindow() //inside any WPF Window constructor
{
...
//add this one statement to bind a new keyboard command shortcut
InputBindings.Add(new KeyBinding( //add a new key-binding, and pass in your command object instance which contains the Execute method which WPF will execute
new WindowCommand(this)
{
ExecuteDelegate = TogglePause //REPLACE TogglePause with your method delegate
}, new KeyGesture(Key.P, ModifierKeys.Control)));
...
}
創建一個簡單的WindowCommand類,它接受一個執行委托來觸發它上面的任何方法集。
public class WindowCommand : ICommand
{
private MainWindow _window;
//Set this delegate when you initialize a new object. This is the method the command will execute. You can also change this delegate type if you need to.
public Action ExecuteDelegate { get; set; }
//You don't have to add a parameter that takes a constructor. I've just added one in case I need access to the window directly.
public WindowCommand(MainWindow window)
{
_window = window;
}
//always called before executing the command, mine just always returns true
public bool CanExecute(object parameter)
{
return true; //mine always returns true, yours can use a new CanExecute delegate, or add custom logic to this method instead.
}
public event EventHandler CanExecuteChanged; //i'm not using this, but it's required by the interface
//the important method that executes the actual command logic
public void Execute(object parameter)
{
if (ExecuteDelegate != null) //let's make sure the delegate was set
{
ExecuteDelegate();
}
else
{
throw new InvalidOperationException("ExecuteDelegate has not been set. There is no method to execute for this command.");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.