在 C#/Windows 窗体中检测应用程序启动时的 Shift 键
有没有办法让标准 Windows 窗体应用程序检测在应用程序启动时是否按住 Shift 键 - 而不使用 Windows 挂钩?
理想情况下,如果在运行 EXE 文件时按住 Shift 键,工作流程会从正常情况改变。
Is there a way to get a standard Windows Forms application to detect if the Shift key is being held down on application startup - without using Windows hooks?
I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
ModifierKeys 属性看起来很理想:
The ModifierKeys property looks ideal:
我意识到这已经非常古老了,但看到人们为此苦苦挣扎,我有点困扰。 ModifierKeys 是一个位字段,因此依靠 .ToString() 或 == 来查看是否按下 Shift 键充其量是不可靠的,并且不是位字段的正确使用:
没有或 Alt、可能会按下 Control 或 Shift 键,因此检查应该是:
一旦我获得这样做的权利,我就会对 Dan 的答案进行投票:-) .Net 4+ 也包含 HasFlag() 方法,但我是习惯了按位运算所以没用过。 有关按位运算、标志、真值表和其他花絮的更多信息,请参阅:
http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/22/c-fundamentals-combining-enum-values-with-bit-flags .aspx
您在源代码中看到的内容更加有趣:
此实现仅发出 Shift、Control 和 Alt 的状态。 不包括 Windows 的按键状态。
如果您想在创建表单或控件之前检测按键状态,也许在 Main() 方法中,您可能会发疯。
也许您想要这样做:
创建一个简单的扩展方法:
导入:
创建以下枚举(或者如果您愿意的话,创建一些子部分)(来自 PInvoke):
无论如何,这仅供参考,因此没有太多猜测在。
HTH,
科尔比
I realize this is super old, but it bothered me a little bit to see people struggling with this. ModifierKeys is a bit field, so relying on .ToString() or == to see if the Shift key is pressed is, at best, unreliable and isn't the correct use of a bit field:
Either none or any combination of Alt, Control, or Shift may be pressed, so the check should be:
I will up-vote Dan's answer as soon as I earn the right to do so :-) .Net 4+ includes the HasFlag() method as well, but I am accustomed to bitwise operations so I haven't used it. For more information on bitwise operations, flags, (with) truth tables, and other tidbits see:
http://geekswithblogs.net/BlackRabbitCoder/archive/2010/07/22/c-fundamentals-combining-enum-values-with-bit-flags.aspx
What you see in the source is even more intriguing:
This implementation ONLY emits the state of Shift, Control, and Alt. The Windows' key state is not included.
If you want to detect the key state BEFORE a form or control is created, maybe in the Main() method, you can go crazy.
Maybe you want to to this:
Create a simple extension method:
Import:
Create the following enum (or some sub-section if you please) (from PInvoke):
Anyway, this is just for reference so there isn't so much guessing going on.
HTH,
Colby
检查 Control.ModifierKeys ...
Check Control.ModifierKeys ...
我知道这篇文章相当旧,但我遇到了这个问题并通过修改 Jamie 的代码来修复它:
I know this post is rather old but I ran into this issue and fixed it by modifying Jamie's code:
这是一篇关于阅读关键状态的文章 (和鼠标)直接。
Here is an article about reading the key states (and mouse) directly.