c# - 实现键盘快捷键

标签 c# wpf

我目前使用 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/

相关文章:

c# - CosmosDb 按 slug 获取项目

c# - 如何使用 C# 连接到 HBase/Hadoop 数据库

c# Image PropertyItems (Metadate) 你怎么知道哪个数字是哪个属性?

c# - 以编程方式禁用 Windows 7 上的虚拟键盘?

c# - 如何通过.resources.dll停止扫描

c# - 自定义身份验证模块仅在存在凭据时调用

c# - 如何使用字符串值创建类似枚举的对象?

wpf - 在 WPF 中创建页面或窗口

c# - 从数据库检查登录凭据

c# - 从 XAML 加载 ResourceDictionary 也会将文件加载到内存中