c++ - 全局 Hook 是否可以跨 x86 和 x64 工作

标签 c++ winapi hook

我试图将所有内容嵌入到一个 COM dll 中。目前我按如下方式连接了 WH_GETMESSAGE 和 WH_CBT:

BOOL TouchDetector::SetMessageHook(BOOL Install)
{
if (Install)
{
    return ((mHookMessage = ::SetWindowsHookEx(WH_GETMESSAGE, MessageHookProc, mDll, 0)) != NULL)
         && ((mHookWin = ::SetWindowsHookEx(WH_CBT, WinHookProc, mDll, 0)) != NULL);
}
else
{
    return UnhookWindowsHookEx(mHookMessage)
        && UnhookWindowsHookEx(mHookWin);
}
};

我也像这样放置共享变量:

#pragma data_seg(".shared")
TouchDetector*   pTouch = nullptr;
HHOOK            mHookMessage = NULL;
HHOOK            mHookWin = NULL;
#pragma data_seg()
#pragma comment(linker,"/section:.shared,rws")

通过附加到 explorer.exe,我可以看到 Hook 正在工作但不是全局的。 我也尝试了 SetWinEventHook,但结果相同:仅对我创建的窗口或 explorer.exe 使用react。

它自己的 COM dll 是 x64,因为资源管理器是 x64。这可能是问题所在吗?

我试图存档的是在前台窗口更改时更新我的​​应用程序配置。我知道我可以简单地启动另一个线程来关注它。但我不喜欢这样,目前该程序只能被动地响应用户输入或赢得回调。

最佳答案

来自SetWindowsHookEx documentation :

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 call SetWindowsHookEx to inject a 32-bit DLL into 32-bit processes, and a 64-bit application call SetWindowsHookEx to inject a 64-bit DLL into 64-bit processes. The 32-bit and 64-bit DLLs must have different names.

To hook all applications on the desktop of a 64-bit Windows installation, install a 32-bit global hook and a 64-bit global hook, each from appropriate processes, and be sure to keep pumping messages in the hooking application to avoid blocking normal functioning.

The global hooks are a shared resource, and installing one affects all applications in the same desktop as the calling thread.

因此您需要创建两个版本的 DLL,一个用于 32 位 Hook ,一个用于 64 位 Hook 。如果您稍后决定添加 WH_MOUSEWH_KEYBOARDWH_JOURNAL*WH_SHELL 全局 Hook ,请小心:

Be aware that the WH_MOUSE, WH_KEYBOARD, WH_JOURNAL*, WH_SHELL, and low-level hooks can be called on the thread that installed the hook rather than the thread processing the hook. For these hooks, it is possible that both the 32-bit and 64-bit hooks will be called if a 32-bit hook is ahead of a 64-bit hook in the hook chain.

但是对于您的 WH_GETMESSAGEWH_CBT Hook ,您应该可以使用同一 DLL 的两个版本。

关于c++ - 全局 Hook 是否可以跨 x86 和 x64 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22885201/

相关文章:

c++ - 如何将多维数组传递给C++中的头文件

c++ - 在 CreateWindow 上设置 HWND 似乎失败

c++ - 为 Windows 7 开发设置为 32 位

winapi - 链接 Windows API

c - 使用 netfilter hook 时打印 skb 数据会使计算机崩溃

c++ - CallWindowProc()生成错误5(访问被拒绝)

c++ - 如何禁用 getter 返回的临时写入?

wpf - 删除最大化 WPF 自定义窗口的 DropShadow

java - Liferay 中的布局(页面)深复制

hook - Drupal 8 模块开发 : hook_node_access not called