另外一个比较方便安全的方案就是用 Windows Accessbility API 的 SetWinEventHook 函数, 监听 EVENT_SYSTEM_SWITCHSTART 和 EVENT_SYSTEM_SWITCHEND 事件。
EVENT_SYSTEM_SWITCHEND The user has released ALT+TAB. This event is sent by the system, never by servers. The hwnd parameter of the WinEventProc callback function identifies the window to which the user has switched.
示例代码:
//安装Event Hook
void InstallEventHook()
{
g_hWinEventhook = ::SetWinEventHook(
EVENT_SYSTEM_SWITCHSTART , EVENT_SYSTEM_SWITCHEND, // NULL, // Handle to DLL.
s_HandleWinEvent, // The callback.
0, 0, // Process and thread IDs of interest (0 = all)
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // Flags.
}
// 回调函数
void CALLBACK s_HandleWinEvent(HWINEVENTHOOK hook, DWORD eventWin, HWND hwnd,
LONG idObject, LONG idChild,
DWORD dwEventThread, DWORD dwmsEventTime)
{
switch (eventWin)
{
case EVENT_SYSTEM_SWITCHSTART:
TRACE0("[EVENT_SYSTEM_MENUSTART] "); // Alt +Tab 被按下
break;
case EVENT_SYSTEM_SWITCHEND:
TRACE0("[EVENT_SYSTEM_MENUEND] "); // Alt +Tab 被松开
break;
}
TRACE1("hwnd=0x%.8x\n", hwnd);
}