Windows 中 Alt + Tab 組合鍵被用來在各個程序之間切換。 因此,該鍵盤消 息 (WM_KEYDOWN/UP) 是直接發給系統內核, 在應用程序中的消息循環中截獲不 到。
一個常見問題是,可是有的應用程序想在被Alt+TAB 切換到後台之間做點事情 , 這時候該怎麼辦?
方案之一就是用底層的鍵盤鉤子,截獲整個系統的鍵盤輸入。但這樣做會導致 一些效率以及穩定性問題。
另外一個比較方便安全的方案就是用 Windows Accessbility API 的 SetWinEventHook 函數, 監聽 EVENT_SYSTEM_SWITCHSTART 和 EVENT_SYSTEM_SWITCHEND 事件。
這2個事件就是對應用戶按下Alt+Tab鍵 以及 松開 Alt+Tab鍵,下面是MSDN的 解釋:
EVENT_SYSTEM_SWITCHSTARTThe user has pressed ALT+TAB, which activates the switch window. 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 is switching.
If only one application is running when the user presses ALT+TAB, the system sends an EVENT_SYSTEM_SWITCHEND event without a corresponding EVENT_SYSTEM_SWITCHSTART event.
EVENT_SYSTEM_SWITCHENDThe 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.
If only one application is running when the user presses ALT+TAB, the system sends this event without a corresponding EVENT_SYSTEM_SWITCHSTART event.
示例代碼:
//安裝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%.8xn", hwnd); }