这是这个问题的后续:Alt Tab覆盖Win32识别器。
我尝试捕捉alt-tab切换菜单打开(和退出)的时刻,使用Winuser API中的SetWinEventHook函数。但是,钩子不会捕获任何事件(例如最小化窗口),因此不会调用 HandleWinEvent。
以下代码深受 MSDN 页面上提供的代码的启发
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#ifndef WINVER
#define WINVER 0x0501
#endif
#include "conio.h"
#include <windows.h>
#include <iostream>
// Global variable.
HWINEVENTHOOK g_hook;
// Prototype
void HandleWinEvent(HWINEVENTHOOK , DWORD , HWND ,
LONG , LONG ,
DWORD , DWORD );
// Initializes COM and sets up the event hook.
//
void InitializeMSAA()
{
CoInitialize(NULL);
g_hook = SetWinEventHook(
EVENT_MIN ,EVENT_MAX, // Range of events .
NULL, // Handle to DLL.
HandleWinEvent, // The callback.
0, 0, // Process and thread IDs of interest (0 = all)
WINEVENT_OUTOFCONTEXT ); // Flags.
}
// Unhooks the event and shuts down COM.
//
void ShutdownMSAA()
{
UnhookWinEvent(g_hook);
CoUninitialize();
}
// Callback function that handles events.
//
void HandleWinEvent(HWINEVENTHOOK hook, DWORD event, HWND hwnd,
LONG idObject, LONG idChild,
DWORD dwEventThread, DWORD dwmsEventTime)
{
std::cout << std::hex << event ; // desperate attempt to see if any event is caught
if (event == EVENT_SYSTEM_SWITCHSTART)
{
std::cout << "Begin" ;
}
else if (event == EVENT_SYSTEM_SWITCHEND)
{
std::cout << "End ";
}
}
int main()
{
InitializeMSAA();
while( getch()!= 'q' ){;}
ShutdownMSAA();
return 0;
}
建筑命令:
g++ -o alttab main.cpp -luser32 -lole32
我正在使用带有MinGW/GCC编译器的Windows XP,版本4.5。
来自 MSDN:调用 SetWinEventHook 的客户端线程必须具有消息循环才能接收事件。您的主线程等待"q"按钮,而不运行消息循环。