在我的线程上下文中调用 `SetWindowsHookEx` 函数
为了在 GUI 应用程序中使用 SetWindowsHookEx,您通常希望在事件发生时在线程中调用一个函数。
因此,例如,如果我正在制作一个软件来显示系统上按下的所有按键,我希望我的 GUI 应用程序能够在按下按键时调用函数 AddKeyToList(int vkeycode)
。
我不是 Windows 内部的专家,但如果我正确理解文档,由 SetWindowsHookEx
安装的钩子将在导致钩子事件的线程上下文中被调用。因此,为了完成我所描述的操作,需要:
创建一个包含钩子函数的 DLL,并在其中创建一个所有线程将通过它共享和相互通信的共享内存区域。
在钩子函数和 GUI 程序中创建类似
pInvoke
的机制。在我们的示例中,挂钩函数会将按下的键发送到 GUI 程序,GUI 程序将在其自己的上下文中调用AddKeyToList
函数。
对于一个相对简单的类来说,这是极其复杂的(与 Unix 世界中的 XRecord 扩展相比),如果您使用 Qt 之类的东西,这甚至是不可能的。
是否有任何库(最好是开源的)已经实现了这些机制,并使我能够使用“外观”,例如,每当 WH_KEYBOARD_LL 时,它将调用在我的线程上下文中的函数发生?
我的分析是否正确,或者是否有更简单的方法来实现我所描述的目的?
Qt
库可以帮助我完成这项任务吗?
In order to use SetWindowsHookEx
in a GUI application, you usually want in the bottom line to have a function in your thread called whenever an event has occurred.
So for instance if I'm making a software to show all keys being pressed on the system, I want that somehow my GUI app will have the function AddKeyToList(int vkeycode)
called whenever a key is being pressed.
I'm not an expert in the internals of Windows, but if I understand the documentation correctly, hooks installed by SetWindowsHookEx
are being called in the context of the thread which caused the event they're hooking. So in order to do what I described, one needs to:
Create a DLL which will contain the hook function, and create there a shared memory region that all threads would share and communicate with each other through it.
Create a
pInvoke
like mechanism in both the hook function and the GUI program. In our example the hook function will send the key pressed to our GUI program, and the GUI program will invoke in its own context theAddKeyToList
function.
This is incredibly complex for a relatively simple class (compare to the XRecord extension in the unix world), and its maybe even impossible if you use something like Qt
.
Is there any library (preferably open source) which already implemented those mechanisms, and enable me to use a "facade" which, for example, will invoke a function in my thread context whenever a WH_KEYBOARD_LL
occurs?
Am I correct with my analysis, or is there a simpler method to achieve what I described?
Can the Qt
library help me with this task?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这已经是 WH_KEYBOARD_LL 挂钩的默认行为。该回调在调用 SetWindowsHookEx() 的同一线程中调用。该线程还必须泵送一个消息循环,以便在您使用 UI 线程时自动正常工作。而且回调代码也不需要出现在 DLL 中,它不是需要 DLL 注入的全局钩子。
不需要做额外的工作。
That's already the default behavior for a WH_KEYBOARD_LL hook. The callback is called in the same thread that called SetWindowsHookEx(). That thread must also pump a message loop for this to work properly, automatic when you use your UI thread. And the callback code doesn't need to be present in a DLL either, it is not a global hook that requires DLL injection.
No extra work needs to be done.