如何捕获组合键事件? [英] How to capture combination key event?

查看:61
本文介绍了如何捕获组合键事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中,它是这样写的:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.Shift && e.KeyCode == Keys.P)
    {
        MessageBox.Show("Hello");
    }
}

捕获Ctrl + Shift +C#Windows Forms应用程序中的P按键[重复]

我试图模仿他们在 C#中将其写到 Delphi XE8 方式,但是它似乎不起作用:

I tried to emulate the way they wrote it in C# to Delphi XE8 but it doesn't seemed to work:

procedure TForm12.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (GetKeyState(VK_CONTROL) < 0) and (Key = 53) then
    ShowMessage('You pressed "ctrl + s"');
end;

注意: TForm.KeyPreview Troperty 设置为 true

如何捕获该组合键事件?

How can I capture that combination key event?

推荐答案

您要查找的密钥 S 的代码为 $ 53 .您指定的密钥的代码为 53 ,并且为数字 5 .区别在于 $ 表示十六进制.

The key you are looking for, S, has code $53. The key you specified has code 53 and is the number 5. The difference is the $ which signifies hexadecimal.

如果让编译器完成工作,您将避免此类愚蠢的错误,并使代码更加清晰:

You'd avoid such silly mistakes, and make the code much clearer, if you let the compiler do the work:

Key = ord('S')

您真的不想在程序中使用魔术常数.那很重要.

You really don't want to use magic constants in your program. That is very important.

请注意, Key 虚拟键代码,惯例是拉丁字母的26个键由大写字母的序号表示.

Note that Key is a virtual key code and the convention is that for the 26 keys of the Latin alphabet, they are represented by the ordinal value of the uppercase letter.

消息已通过 Shift键中的修饰键状态 参数,因此按如下方式编写测试是很习惯的:

The message already passes the state of the modifier keys in the Shift argument, so it is idiomatic to write the test as follows:

if (ssCtrl in Shift) and (Key = ord('S')) then

您使用 GetKeyState 进行的测试效果很好,但这不是惯用的.

Your test using GetKeyState does work well, but it's just not idiomatic.

请注意,此测试与问题中的测试匹配,将忽略其他修饰键的状态.确实,问题中的C#代码也忽略了 ALT 修饰符的状态.

Note that this test, which matches that in the question will, ignores the state of the other modifier keys. Indeed, the C# code in the question also ignores the state of the ALT modifier.

因此,您可能需要对 CTRL + S 进行真实测试,还必须检查其他修饰符是否已启用:

So you may want a true test for CTRL + S you must also check that the other modifiers are up:

if ([ssCtrl] = Shift*[ssCtrl, ssShift, ssAlt]) and (Key = ord('S')) then

所有这些,通常使用操作来管理快捷方式通常要容易得多.这将允许您直接指定快捷方式,并让框架检测组成快捷方式的低级键事件.此外,动作还使您可以集中处理按钮和菜单后面的动作,而无需重复操作.

All this said, it's usually much easier to manage your shortcuts using actions. This will allow you to specify shortcuts directly, and let the framework detect the low level key events that make up a shortcut. What's more actions allow you to centralise handling of the actions behind buttons and menus without you repeating yourself.

这篇关于如何捕获组合键事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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