对于如何使用和创建钩子有许多的争议,这篇文章试图澄清这些问题。 注意:如果你只是在自己的进程内使用钩子则不会有下面的问题, 这只发生在你使用系统钩子的时候。 关键问题在于 地址空间,DLL函数中的代码所创建的任何对象(包括变量)都归调用它的线程或进程所有。当进程在载入DLL时,操作系统自动把DLL地址映射到该进程的私有空间,也就是进程的虚拟地址空间,而且也复制该DLL的全局数据的一份拷贝到该进程空间。也就是说每个进程所拥有的相同的DLL的全局数据,是私有的,DLL成为进程的一部分,以这个进程的身份执行,使用这个进程的堆栈。这意味着数据会被重新初始化。典型地,它们将是零。 有人建议在DLL上存放数据的地址。 这是不可能的。有人反对? 那好,这不是不可能的,但这是不可能有什么 用途 的。既使你创建的是对DLL 的所有实例可见的共享内存变量,这一变量只有在储存它的进程中才有实际的意义。 对于所有其它的进程,这仅仅是一串比特位,并且如果你设法使用它作为地址,对于事件被拦截的进程而言,这个地址是完全无用甚至导致程序崩溃。 这个分开的地址空间的概念是一个难以掌握的概念。 让我使用图片说明它。
让我们看一看在进程B会发生什么 。 当事件在进程中B中被钩时,DLL 被映射。代码被迁入到进程中B中另外的一个地址。如果你调试进程中B ,留意在共有的区域中的 &something,你会发现 &something 的地址是不同的,但 &something 的内容会是同样的; 在你的进程中或进程A中对&something的内容做的改变立刻就能在进程B中看见,即使进程B是在另外的一个地址(虚拟地址)看见的。(这是在同样的物理内存地点)。当我提到巧合时,"巧合" 是指被策划; Windows总是试图将DLL映射入同样的虚拟地址, 它试图这么干,但它很少成功。 这就意味着,如果你在DLL中存放了一个指向回调函数的指针,但在实际运行进程A 或进程B时,它可能会指向别的地址。这也意味着你将不能在DLL中使用MFC--它不能是一个扩展MFC DLL或MFC DLL,因为这些DLL(动态链接库)会调用MFC 函数。 那么MFC 函数在哪里? 他们是在你的地址空间, 而不是在进程A或进程B的 地址空间! 因为他们可能是用Visual.basic ,Java或其他语言写的 , 所以你必须写straight-C DLL ,并且我建议你忽略整个C runtime library.,只使用API 。 用lstrcpy 代替 strcpy 或 tcscpy,用 lstrcmp 代替 strcmp 或 tcscmp,等等。 如何让你的DLL与其controlling server 通信?
一种解答将使用 ::PostMessage 或 ::SendMessage 函数。(我这里提到的是原始API 的调用,不是MFC 的调用!) 每当可能使用 ::PostMessage时,尽可能使用它优先于使用 ::SendMessage。否则,如果你的进程不幸停止,因为大家都被阻拦在一个永远不会返回的::SendMessage,其他进程也将停止,然后是整个系统都停止。 你也可以考虑在共享内存区域使用信息队列,但那个题目在这篇文章范围之外。 在 ::SendMessage 或 ::PostMessage中,你无法传回一个指针 (我们将忽略传回一个相对指针进入共享内存区域的问题; 那也是在这篇文章范围之外). 这是因为你能使用的任一指针指示的地址要么是在DLL 中, 要么是在在被钩的进程中。(进程A 或进程B) 因此在你的进程中,这个指针是完全无用的。 你只能通过在 WPARAM 或 LPARAM中的信息传回地址空间。 I 我强烈 建议为此使用登记的窗口消息。 你能发送消息到 MESSAGE_MAP(消息映射) 窗口,并在此使用 ON_REGISTERED_MESSAGE 宏指令。 现在关键是要得到 那个窗口的HWND(句柄)。 幸运的是,这很容易。
你必须做的第一件事是创建共有的数据段。 所以我们使用 # pragma data_seg 声明。 使用某一好记的数据段名字(它必须是没有比8 个字符长) 。我想强调名字是任意的,这里使用了我自己的名字。 我发现如果我使用好的名字象 # pragma data_seg(".JOE") HANDLE hWnd = NULL; # pragma dta_seg() # pragma comment(linker ,"/ section:.JOE,rws ") # pragma 声明一个数据段,在此范围内声明的变量在初始化后将被指派到该数据段, 假设他们初始化. 如未初始化,变量将被分配到缺省数据段,而# pragma 不起作用。 初看起来, 这将阻止你在共有的数据段使用一些C++ 对象,因为你无法初始化C++中用户定义的对象。 这看来是一个根本局限。 # pragma comment 使连接器有命令行开关被显示增加到链接步骤。 你可以进入VC++ 项目| 设置 并且改变连接器命令行。 你可以预定某一机制设置窗口句柄,例如 void SetWindow(HWND w) {hWnd = w; }
但更经常的是如下所示的与钩子结合。 Sample: A Mouse Hookheader file (myhook.h)
函数 setMyHook 并且 clearMyHook 必须在此被声明。这在我的另一文章中有详细论述。“The Ultimate DLL Header File.” #define UWM_MOUSEHOOK_MSG \ _T("UMW_MOUSEHOOK-" \ "{B30856F0-D3DD-11d4-A00B-006067718D04}")
source file (myhook.cpp)#include "stdafx.h" #include "myhook.h"
#pragma data_seg(".JOE") HWND hWndServer = NULL; #pragma data_seg() #pragma comment("linker, /section:.JOE,rws")
HINSTANCE hInstance; UINT HWM_MOUSEHOOK; HHOOK hook;
// Forward declaration static LRESULT CALLBACK msghook(int nCode, WPARAM wParam, LPARAM lParam); /**************************************************************** * DllMain * Inputs: * HINSTANCE hInst: Instance handle for the DLL * DWORD Reason: Reason for call * LPVOID reserved: ignored * Result: BOOL * TRUE if successful * FALSE if there was an error (never returned) * Effect: * Initializes the DLL. ****************************************************************/
BOOL DllMain(HINSTANCE hInst, DWORD Reason, LPVOID reserved) { switch(Reason) { /* reason */ //********************************************** // PROCESS_ATTACH //********************************************** case DLL_PROCESS_ATTACH: // Save the instance handle because we need it to set the hook later hInstance = hInst; // This code initializes the hook notification message UWM_MOUSEHOOK = RegisterWindowMessage(UWM_MOUSEHOOK_MSG); return TRUE;
//********************************************** // PROCESS_DETACH //********************************************** case DLL_PROCESS_DETACH: // If the server has not unhooked the hook, unhook it as we unload if(hWndServer != NULL) clearMyHook(hWndServer); return TRUE; } /* reason */ /**************************************************************** * setMyHook * Inputs: * HWND hWnd: Window whose hook is to be set * Result: BOOL * TRUE if the hook is properly set * FALSE if there was an error, such as the hook already * being set * Effect: * Sets the hook for the specified window. * This sets a message-intercept hook (WH_GETMESSAGE) * If the setting is successful, the hWnd is set as the * server window. ****************************************************************/
__declspec(dllexport) BOOL WINAPI setMyHook(HWND hWnd) { if(hWndServer != NULL) return FALSE; hook = SetWindowsHookEx( WH_GETMESSAGE, (HOOKPROC)msghook, hInstance, 0); if(hook != NULL) { /* success */ hWndServer = hWnd; return TRUE; } /* success */ return FALSE; } // SetMyHook
/**************************************************************** * clearMyHook * Inputs: * HWND hWnd: Window whose hook is to be cleared * Result: BOOL * TRUE if the hook is properly unhooked * FALSE if you gave the wrong parameter * Effect: * Removes the hook that has been set. ****************************************************************/ __declspec(dllexport) BOOL clearMyHook(HWND hWnd) { if(hWnd != hWndServer) return FALSE; BOOL unhooked = UnhookWindowsHookEx(hook); if(unhooked) hWndServer = NULL; return unhooked; } /**************************************************************** * msghook * Inputs: * int nCode: Code value * WPARAM wParam: parameter * LPARAM lParam: parameter * Result: LRESULT * * Effect: * If the message is a mouse-move message, posts it back to * the server window with the mouse coordinates * Notes: * This must be a CALLBACK function or it will not work! ****************************************************************/
static LRESULT CALLBACK msghook(int nCode, WPARAM wParam, LPARAM lParam) { // If the value of nCode is < 0, just pass it on and return 0 // this is required by the specification of hook handlers if(nCode < 0) { /* pass it on */ CallNextHookEx(hook, nCode, wParam, lParam); return 0; } /* pass it on */
// Read the documentation to discover what WPARAM and LPARAM // mean. For a WH_MESSAGE hook, LPARAM is specified as being // a pointer to a MSG structure, so the code below makes that // structure available
LPMSG msg = (LPMSG)lParam;
// If it is a mouse-move message, either in the client area or // the non-client area, we want to notify the parent that it has // occurred. Note the use of PostMessage instead of SendMessage if(msg->message == WM_MOUSEMOVE || msg->message == WM_NCMOUSEMOVE) PostMessage(hWndServer, UWM_MOUSEMOVE, 0, 0);
// Pass the message on to the next hook return CallNextHookEx(hook, nCode, wParam, lParam); } // msghook The server application在头文件中,将下面的增加到类的protected段: afx_msg LRESULT OnMyMouseMove(WPARAM,LPARAM);
在application 文件中, 增加以下代码到文件前部。 UINT UWM_MOUSEMOVE = ::RegisterWindowMessage(UWM_MOUSEMOVE_MSG);
在 //{AFX_MSG comments: ON_REGISTERED_MESSAGE(UWM_MOUSEMOVE, OnMyMouseMove)
In your application file, add the following function: LRESULT CMyClass::OnMyMouseMove(WPARAM, LPARAM) { // ...do stuff here return 0; }
你可以下载这个项目并建立它。 真正的关键是DLL 子工程项目; 其他的都不过是陪衬。有几个其它的技术被用在这个例子里,包括各种各样的图画技术, ClipCursor 和 SetCapture的用法,区域选择、屏幕更新等等。,因此除了展示钩子函数的使用以外,对初级程序员掌握窗口样式设计编程也有一些价值。 |
|