在 Windows 窗体应用程序中实现键盘快捷键的最佳方法? [英] Best way to implement keyboard shortcuts in a Windows Forms application?

查看:24
本文介绍了在 Windows 窗体应用程序中实现键盘快捷键的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找实现常见 Windows 键盘快捷键的最佳方法(例如 Ctrl+FCtrl+N) 在我的 Windows Forms 应用程序中使用 C#.

I'm looking for a best way to implement common Windows keyboard shortcuts (for example Ctrl+F, Ctrl+N) in my Windows Forms application in C#.

该应用程序有一个主窗体,它承载许多子窗体(一次一个).当用户点击 Ctrl+F 时,我想显示自定义搜索表单.搜索表单将取决于应用程序中当前打开的子表单.

The application has a main form which hosts many child forms (one at a time). When a user hits Ctrl+F, I'd like to show a custom search form. The search form would depend on the current open child form in the application.

我想在 ChildForm_KeyDown 事件中使用类似的东西:

I was thinking of using something like this in the ChildForm_KeyDown event:

   if (e.KeyCode == Keys.F && Control.ModifierKeys == Keys.Control)
        // Show search form

但这行不通.当您按下某个键时,该事件甚至不会触发.有什么解决办法?

But this doesn't work. The event doesn't even fire when you press a key. What is the solution?

推荐答案

您可能忘记设置表单的 KeyPreview 属性为 True.覆盖 ProcessCmdKey() 方法是通用解决方案:

You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == (Keys.Control | Keys.F)) {
    MessageBox.Show("What the Ctrl+F?");
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

这篇关于在 Windows 窗体应用程序中实现键盘快捷键的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆