VB.NET 最小化时检测按键
我希望能够检测到用户何时在程序之外按下 F10 或 Ctrl+F10,并且在收到按键后,它将向他们当前选择的任何内容(例如文本框)发送文本。如何以最简单的方式实现这一点?
I want to be able to detect when the user presses F10 or Ctrl+F10 outside of my program, and upon receiving the key press, it will send text to whatever they currently have selected (e.g. a text box). How can this be accomplished in the simplest way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 RegisterHotkey 而不是键盘挂钩获得全局热键。
请参阅我关于几乎同一问题的旧答案之一:当应用程序未聚焦时监听按键
Use RegisterHotkey and not a keyboard hook to get a global hotkey.
See one of my older answers on almost the same question: listen for a key when the application is not focused
这里的第一个问题是 F10 键已经是 Windows 应用程序的保留键。当用户按下它时,活动应用程序会选择其菜单栏中的第一个菜单。这为用户提供了一种无需使用鼠标即可激活菜单的便捷方式。您提议在全球范围内劫持该功能是不考虑和不恰当的。我建议选择不同的快捷键,最好是尚未具有标准含义的快捷键。
然后,您必须安装低级键盘挂钩( .NET 应用程序支持的唯一挂钩类型)。这是捕获应用程序外部发生的键盘事件的唯一方法。由于您想要检测应用程序不在前台时发生的按键,因此您需要一个全局挂钩。
Stephen Toub 的博客上提供了一个出色的示例。它恰好是用 C# 编写的,但转换为 VB.NET 很简单。如果您更喜欢可以简单地添加到项目中的现有代码的完整基础,您可以尝试 此示例,但请注意,它包含许多您不需要的附加功能。
The first problem here is that the F10 key is already a reserved key for Windows applications. When the user presses it, the active application selects the first menu in its menu bar. This provides a convenient way for users to activate menus without having to use their mouse. Your proposal to hijack that functionality globally is inconsiderate and inappropriate. I suggest choosing a different shortcut key, preferably one that doesn't already have a standard meaning.
Then, you will have to install a low-level keyboard hook (the only type of hook supported by .NET apps). This is the only way to capture keyboard events that occur outside of your application. Since you want to detect keypresses that occur when your application is not in the foreground, you'll need a global hook.
There's an excellent sample available here on Stephen Toub's blog. It happens to be written in C#, but converting to VB.NET is trivial. If you prefer a full base of existing code that you can simply add to your project, you can try this sample, but note that it includes a lot of additional functionality you won't need.
您可以在按键事件中检查:
You can check that in the keypress event: