这是这个问题的后续:Alt Tab 覆盖 Win32 标识符。
我尝试使用 Winuser API 中的 SetWinEventHook 函数来捕捉 alt-tab 开关菜单打开(和退出)的时刻。但是,钩子不会捕获任何事件(例如最小化窗口),因此不会调用 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
我正在使用 Windows XP 和 MinGW/GCC 编译器,版本 4.5。