2014-07-10 22:12:59|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C/C++, 操作系统|来源:唯设编程网
注意:glhInstance变量用来保存dll的实例句柄,在CMouseHookLibApp类的InitInstance函数中赋值:
BOOL CMouseHookLibApp::InitInstance() { CWinApp::InitInstance(); glhInstance = AfxGetInstanceHandle(); return TRUE; }
为了在CMouseHookLibApp中使用glhInstance变量,还需要在stdafx.h头文件添加引用语句:
extern HINSTANCE glhInstance;
启动鼠标钩子的函数StartHook如下:
// CMouseHook 成员函数 BOOL CMouseHook::StartHook(HWND hWnd){ BOOL bRes = FALSE; glhHook = SetWindowsHookEx(WH_MOUSE,MouseProc,glhInstance,0); if(glhHook != NULL){ bRes = TRUE; glhRecWnd = hWnd; } else{ CString strTmp; strTmp.Format(_T("%d"),GetLastError()); MessageBox(hWnd,_T("Start Hook failed, error code:")+strTmp, _T("提示"),MB_OK|MB_ICONERROR); } return bRes; }
该函数的关键是使用SetWindowsHookEx函数启动一个钩子,该函数的原型如下:
HHOOK WINAPI SetWindowsHookEx( _In_ int idHook, _In_ HOOKPROC lpfn, _In_ HINSTANCE hMod, _In_ DWORD dwThreadId );
第一个参数是钩子的id,第二个参数是对应的回调函数,第三个参数是钩子dll对应的句柄,第四个参数对应的线程标志。
需要注意的是:钩子的回调函数是一个HOOKPROC类型函数,该函数类型的声明如下:
typedef LRESULT (CALLBACK* HOOKPROC)(int code, WPARAM wParam, LPARAM lParam);
这个函数不能够是类的成员函数,对应该鼠标钩子的回调函数MouseProc的定义如下:
//钩子处理函数 LRESULT WINAPI MouseProc(int nCode, WPARAM wparam, LPARAM lparam){ LPMOUSEHOOKSTRUCT pMouseHook = (MOUSEHOOKSTRUCT FAR *)(lparam); if(nCode == HC_ACTION && wparam == WM_LBUTTONUP){ SendMessage(glhRecWnd,WM_MOUSEHOOK_MESSAGE, (WPARAM)(pMouseHook->hwnd), MAKELPARAM(pMouseHook->pt.x,pMouseHook->pt.y)); } return CallNextHookEx(glhHook,nCode,wparam,lparam); }
该函数接收鼠标左键抬起消息,并将鼠标所在位置通过SendMessage发送消息给对应的窗口句柄。
停止鼠标钩子通过UnhookWindowsHookEx函数实现,对应的参数是SetWindowsHookEx启动鼠标钩子所对应的钩子句柄:
BOOL CMouseHook::StopHook(){ BOOL bRes = FALSE; if(glhHook){ bRes = UnhookWindowsHookEx(glhHook); if(bRes){ glhHook = NULL; }else{ CString strTmp; strTmp.Format(_T("%d"),GetLastError()); MessageBox(glhRecWnd,_T("Stop Hook failed, error code:")+strTmp, _T("提示"),MB_OK|MB_ICONERROR); } } return bRes; }