后改用WH_MOUSE_LL方可捕捉全局事件。
相关代码组织:
1.首先建立一个DLL,可以直接选择win32 dynamic-link library建立相应的工程。代码大致如下
#include "stdafx.h" #include "msgh.h" #pragma data_seg("ShareData") HHOOK g_Hook= NULL; HWNDg_Hwnd = NULL; DWORD g_dwMsg= 0; HINSTANCE g_hHINS = NULL; #pragma data_seg() // //SECTIONS // ShareDataREAD WRITE SHARED BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { g_hHINS =(HINSTANCE)hModule; switch(ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } returnTRUE; } LRESULT CALLBACK MouseProc( intnCode,// hook code WPARAM wParam, // messageidentifier LPARAMlParam // mousecoordinates ) { // if(HC_ACTION == nCode) { //if (WM_MOUSEMOVE == wParam) { SendMessage(g_Hwnd, g_dwMsg, wParam,lParam); //return 1; } } returnCallNextHookEx(g_Hook, nCode, wParam, lParam); } extern "C" MSGH_API void installHook(HWND hWnd, DWORD dwMsg) { g_Hwnd =hWnd; g_dwMsg =dwMsg; g_Hook =SetWindowsHookEx(WH_MOUSE_LL, MouseProc, g_hHINS, 0); DWORD dwE =GetLastError(); DWORD k =dwE; } |
注:
1. 此工程不需要def文件
2. 网上其它例子中, 有如下形式之一
#pragmacomment(linker,"/section:ShareData,RWS")
或在DEF文件中加入下面的内容
SECTIONS
ShareDataREAD WRITE SHARED
经过在我的WINXP,SP2+VC6,SP5测试,如果加入了上面的二者之一,那么程序在运行时,会引起系统停止响应以及程序崩溃。故不采用!!!!
接下来,在你的应用工程插入下面的代码,以安装HOOK并使其将收到的消息用指定消息ID(WM_MM)传到你的相应处理WM_MM的窗口(m_hWnd),由其进行处理。注意使用时WH_MOUSE_LL,其收到的hook消息结构是MSLLHOOKSTRUCT类型。这一点通过查阅MSDN的SetWindowsHookEx可知!
应用示例代码
typedef void (*installHook)(HWND,DWORD); #define WM_MM (WM_USER + 2) HINSTANCEhIN = LoadLibrary("msgh.dll");———— if (NULL ==hIN) return; installHookkk = (installHook)GetProcAddress(hIN, "installHook"); kk(m_hWnd,WM_MM); 而处理WM_MM的示例代码节选如下 LRESULT CTestDlg::OnMm(WPARAM wParam, LPARAM lParam) { CStringobjTip; MSLLHOOKSTRUCT* pp = (MSLLHOOKSTRUCT*)lParam; objTip.Format("%d, %d", pp->pt.x,pp->pt.y); SetWindowText(objTip); } |
2011.10.11 在VS2008上面,测试发现,要以下列的方式
#pragma data_seg("ShareData")
HHOOK g_Hook= NULL;
HWNDg_Hwnd = NULL;
DWORD g_dwMsg= 0;
HINSTANCE g_hHINS = NULL;
#pragma data_seg()
#pragmacomment(linker,"/SECTION:ShareData,RWS")
进行使用,才能进行数据共享。