全局 Windows Hook 必须在 DLL 中,因为 Hook 将在不同进程的上下文中调用,因此 Hook 过程的代码必须注入(inject)该进程。但是,有limitations :
SetWindowsHookEx
can be used to inject a DLL into another process. A 32-bit DLL cannot be injected into a 64-bit process, and a 64-bit DLL cannot be injected into a 32-bit process. If an application requires the use of hooks in other processes, it is required that a 32-bit application callSetWindowsHookEx
to inject a 32-bit DLL into 32-bit processes, and a 64-bit application callSetWindowsHookEx
to inject a 64-bit DLL into 64-bit processes. The 32-bit and 64-bit DLLs must have different names.
出于这个原因,我宁愿使用低级 Hook WH_MOUSE_LL
和 WH_KEYBOARD_LL
,而不是 WH_MOUSE
和 WH_KEYBOARD
。从 their 看到documentation :
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.
这使我认为这些特定的 Hook 程序不需要位于单独的 DLL 中,而可以直接存在于将它们 Hook 的 EXE 中。 documentation for SetWindowsHookEx
,然而,说:
lpfn
[in] Pointer to the hook procedure. If the
dwThreadId
parameter is zero or specifies the identifier of a thread created by a different process, thelpfn
parameter must point to a hook procedure in a DLL.
没有提到两个低级 Hook 的明确异常(exception)。
我见过几个使用低级钩子(Hook)的 .NET 应用程序,它们的钩子(Hook)过程没有放在单独的 DLL 中。这是另一个暗示这是可以接受的。但是,我有点害怕自己这样做,因为文档禁止这样做。
如果我不使用 DLL 而只是将这些低级 Hook 程序直接放入我的 EXE 中,有人预见到会有什么麻烦吗?
编辑:对于赏金,我想要一个明确的“是的,这没关系,因为......”或“不,这可能会出错,因为......”。
最佳答案
原来这个是实际上在文档中。虽然不在SetWindowsHookEx
和 friend 的文档中,但是在a .NET knowledge base article .
Low-level hook procedures are called on the thread that installed the hook. Low-level hooks do not require that the hook procedure be implemented in a DLL.
关于winapi - 我可以将 LowLevelMouseProc 和 LowLevelKeyboardProc 放在主 EXE 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1639496/