【问题标题】:How to set hook for mouse clicked on particular application only如何设置仅在特定应用程序上单击鼠标的挂钩
【发布时间】:2018-05-28 09:29:03
【问题描述】:
我正在使用以下代码在鼠标单击事件上创建鼠标钩子:
mousehook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0);
可以在鼠标点击时调用MouseHookProc函数。
但是,如果我单击其他应用程序或普通桌面屏幕,仍会调用此 MouseHookProc 函数。
我如何才能将此钩子事件仅限于我当前的应用程序?
【问题讨论】:
标签:
c++
windows
mouseevent
setwindowshookex
【解决方案1】:
首先,我认为如果您只是在应用程序中查找鼠标事件,您可能只使用主消息泵而不是挂钩。
但是,使用低级鼠标挂钩,这将处理您的应用程序中的工作,并且在另一个应用程序中时不会干扰
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);
}