1)下钩
HHOOK g_hook = NULL;
g_hook = SetWindowsHookEx(//WH_MOUSE//设置鼠标钩子
WH_MOUSE_LL//设置键盘钩子 WH_KEYBOARD_LL
, MessageBoxProc, GetModuleHandle(NULL), NULL);
2)卸钩
if(g_hook)
UnhookWindowsHookEx(g_hook);//卸载HOOk函数
3)钩子函数
LRESULT CALLBACK MessageBoxProc(
INT nCode, WPARAM wParam, LPARAM lParam
)
{
//if (nCode < 0)
//return CallNextHookEx(g_hook, nCode, wParam, lParam);
if (nCode == HC_ACTION)
{
PMSG pMsg = (PMSG)lParam;
DWORD temp = pMsg->message;
if (temp == WM_RBUTTONDOWN)//WM_RBUTTONDOWN
{
CString strMsg = "Hook Ok";
AfxMessageBox(strMsg);
}
if ((wParam == WM_KEYDOWN) && (HC_ACTION == nCode))
{
//有键按下
KBDLLHOOKSTRUCT* keyNum = (KBDLLHOOKSTRUCT *)lParam;
std::cout << "MessageBoxProc key" << keyNum->vkCode << std::endl;
}
MOUSEHOOKSTRUCT * pMouseStruct = (MOUSEHOOKSTRUCT *)lParam;
if (pMouseStruct != NULL) {
CWnd *pWnd = NULL;
HWND hwndFind = NULL;
if (wParam == WM_RBUTTONDOWN)
{
std::cout << "MessageBoxProc WM_RBUTTONDOWN x,y " << pMouseStruct->pt.x << ", " << pMouseStruct->pt.y << std::endl;
HWND hwndFind = GetChildMost(pMouseStruct->pt);
if (hwndFind)
pWnd = CWnd::FromHandle(hwndFind);
if (pWnd)
{
CString strText;
pWnd->GetWindowText(strText);
UINT nID = GetDlgCtrlID(hwndFind);
std::cout << "pMouseStruct->hwnd nID: "<<nID<<" text: " << strText << std::endl;
}
//
}
//else if (wParam == WM_MOUSEMOVE)
//{
// std::cout << "MessageBoxProc WM_MOUSEMOVE x,y " << pMouseStruct->pt.x << ", " << pMouseStruct->pt.y << std::endl;
//}
}
}
return CallNextHookEx(g_hook, nCode, wParam, lParam);
}