C++使用 Windows 挂钩自定义热键
我想制作一些自定义热键,在任何程序中我都可以使用某些组合键调出不同的程序。我研究了如何做钩子并给出了这个例子。
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
// Set windows hook
HHOOK keyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
keyboardHookProc,
hInstance,
0);
MessageBox(NULL, "Press OK to stop hot keys", "Information", MB_OK);
return 0;
}
因为我希望它在后台运行,所以我尝试使用循环,而不是消息框,但我成功尝试过的所有行为都不像消息框。有什么想法吗?
I want to make some custom hot keys where in any program I can bring up different programs with certain key combinations. I researched how to do hooks and was given this example.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
// Set windows hook
HHOOK keyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
keyboardHookProc,
hInstance,
0);
MessageBox(NULL, "Press OK to stop hot keys", "Information", MB_OK);
return 0;
}
Rather than a message box, as I want this to run in the background, I tried using loops but nothing I have tried successfully behaves like the messagebox. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
下面这段代码是一个热键应用程序,它位于后台监听
CTRL-y
组合键,您可以修改或向该应用程序添加更多组合键。隐藏时使用CTRL-q
退出应用程序。如果您希望完全隐藏控制台窗口,请在 main() 中取消注释此行:
//ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false)
。享受。完整代码清单:
This good code below is a Hotkey app that sits in the background listening for the
CTRL-y
key combination, and you can modify or add any more key combinations to the app. UseCTRL-q
to exit the app when hidden.If you wish to fully hide the console window, then un-comment this line in main() :
//ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false)
. Enjoy.Full code listing:
除非绝对需要,否则不要使用 Windows 挂钩。在您的情况下,您可以通过调用
RegisterHotKey
函数,这要简单得多,因为您不需要开发进程间通信(即带有钩子过程的 DLL 和主程序之间的通信) 应用程序)。Don't use windows hooks unless you absolutely need to. In your case you can install a hotkey by calling the
RegisterHotKey
function, which is much simpler since you don't need to develop interprocess communication (that is between your DLL with the hook procedure and your main app).“这个钩子是在安装它的线程的上下文中调用的。调用是通过向安装钩子的线程发送消息来进行的。因此,安装钩子的线程必须有一个消息循环。” - LowLevelKeyboardProc MSDN
您需要创建一个隐形窗口。
"This hook is called in the context of the thread that installed it. The call is made by sending a message to the thread that installed the hook. Therefore, the thread that installed the hook must have a message loop." - LowLevelKeyboardProc MSDN
You need to create an invisible window.
我不确定,但您可能需要一个完整的消息循环,而不是正常的空无限循环。特别是如果您按照 ybungalobil 建议使用 RegisterHotKey 函数。
I'm not sure, but instead of a normal empty infinite loop, you might need to have a complete message loop. Especially if you use the RegisterHotKey function as suggested by ybungalobill.