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_SWITCHSTART The 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_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.
If only one application is running when the user presses ALT+TAB, the system sends this event without a corresponding EVENT_SYSTEM_SWITCHSTART event.
示例代碼:
view plaincopy to clipboardprint?
//安裝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 被松開
}
TRACE1("hwnd=0x%.8x\n", hwnd);
}
本文轉自 陳本峰 51CTO部落格,原文連結:http://blog.51cto.com/wingeek/273996,如需轉載請自行聯系原作者