如何设置仅在特定应用程序上单击鼠标的挂钩

时间:2017-12-14 10:16:44

标签: c++ windows mouseevent setwindowshookex

我正在鼠标点击事件上创建鼠标钩子,代码如下:

mousehook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0);

可以在鼠标单击时调用MouseHookProc函数。

但是,如果我点击其他应用程序或普通桌面屏幕仍然会调用此MouseHookProc函数。 如何仅将此挂钩事件限制为当前应用程序?

1 个答案:

答案 0 :(得分:0)

首先,我认为如果您只在应用程序中查找鼠标事件,则可能只使用主消息泵而不是钩子。

但是,使用低级鼠标挂钩,这将处理您应用中的工作,而不会在其他应用中干扰

MSLLHOOKSTRUCT *hookStruct = (MSLLHOOKSTRUCT*)lParam;
// hMyMainAppHWND in the line below would already be defined 
// and set when your program starts and gets its handle
if(GetAncestor(WindowFromPoint(hookStruct->pt),GA_ROOTOWNER) != hMyMainAppHWND){ 
    // if the owner of the window where the mouse event occurred 
    // isn't your application's owning window, pass the event on
    return CallNextHookEx(mousehook, nCode, wParam, lParam);
} else {
    // The event occurred on your application
    // Do your stuff here
    // Don't forget to do one of the following:
    // if you want to consume the event, making it as though it never happened:
    // return TRUE; 
    // if you want the event to be processed as normal:
    // return CallNextHookEx(mousehook, nCode, wParam, lParam); 
}