如何使用 Win32 挂钩模拟 Alt+Tab?
我使用 VS2010 编写了这个 C++ 程序来检测用户何时双击鼠标中键,切换到下一个窗口(如 Alt+Tab 那样)并停止钩子链。这是我的代码:
DLL:
extern "C"__declspec (dllexport)
LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode<0)
return CallNextHookEx(NULL,nCode,wParam,lParam);
if (wParam == WM_MBUTTONDBLCLK)
{
PostMessage(GetActiveWindow(),WM_SYSCOMMAND,SC_NEXTWINDOW,0);
}
else
return CallNextHookEx(NULL,nCode,wParam,lParam);
// if EVERYTHING_IS_OK
return TRUE;
}
EXE:
do{
nMenu = choose();
switch (nMenu)
{
case 1:
hLib = LoadLibrary(cLibName);
hProc = (HOOKPROC) GetProcAddress(hLib, "HookProc");
hHook = SetWindowsHookEx(WH_MOUSE, hProc, hLib, NULL);
break;
case 2:
UnhookWindowsHookEx(hHook);
break;
case 0:
;
}
} while (nMenu);
我启动程序并设置挂钩,然后程序挂起并且鼠标在大多数应用程序中停止工作(但在 Chrome 中继续工作)。我做错了什么?
I've written this C++ program using VS2010 to detect when the user is making a double middle mouse button click, switch to the next window (as Alt+Tab does) and stop the hook chain. Here's my code:
DLL:
extern "C"__declspec (dllexport)
LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode<0)
return CallNextHookEx(NULL,nCode,wParam,lParam);
if (wParam == WM_MBUTTONDBLCLK)
{
PostMessage(GetActiveWindow(),WM_SYSCOMMAND,SC_NEXTWINDOW,0);
}
else
return CallNextHookEx(NULL,nCode,wParam,lParam);
// if EVERYTHING_IS_OK
return TRUE;
}
EXE:
do{
nMenu = choose();
switch (nMenu)
{
case 1:
hLib = LoadLibrary(cLibName);
hProc = (HOOKPROC) GetProcAddress(hLib, "HookProc");
hHook = SetWindowsHookEx(WH_MOUSE, hProc, hLib, NULL);
break;
case 2:
UnhookWindowsHookEx(hHook);
break;
case 0:
;
}
} while (nMenu);
I launch the program and set the hook, then the program hangs and mouse stops working in most apps (keeps working in Chrome though). What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果钩子不仅仅用作通知,那么它们就是邪恶的。 MSDN 强烈建议调用 CallNextHookEx() 是有原因的。您无法知道您处于调用链中的哪一点。这会使您的代码变得脆弱,即使它一开始看起来可以工作。
您依赖钩子 API 的其他用户对您友善,即给您打电话。如果有人(比如你)不这样做,你的代码就会崩溃。
在不进一步详细说明代码损坏的地方的情况下,我认为这并不奇怪
如果您通过返回
TRUE
来关闭鼠标钩子的其他用户,则Hooks are evil if they are not used as notifications only. The MSDN highly recommends calling
CallNextHookEx()
for a reason. You cannot know at which point in the calling chain you are. This makes your code fragile even though it might appear to work at first.You depend on other users of the hook API to be nice to you, i.e. to call you. If someone (like you) does not do it, your code breaks.
Without going into further detail where your code breaks, I think that it is not very surprising that
if you shut up the other users of the mouse hook by returning
TRUE
, is it?