[Windows 編程] 如何截獲 Alt+Tab 事件

來源:互聯網
上載者:User

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.

 

範例程式碼:

 

//安裝Event Hook<br />void InstallEventHook()<br />{<br /> g_hWinEventhook = ::SetWinEventHook(<br /> EVENT_SYSTEM_SWITCHSTART , EVENT_SYSTEM_SWITCHEND, // NULL, // Handle to DLL.<br /> s_HandleWinEvent, // The callback.<br /> 0, 0, // Process and thread IDs of interest (0 = all)<br /> WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // Flags.</p><p>}</p><p>// 回呼函數</p><p>void CALLBACK s_HandleWinEvent(HWINEVENTHOOK hook, DWORD eventWin, HWND hwnd,<br /> LONG idObject, LONG idChild,<br /> DWORD dwEventThread, DWORD dwmsEventTime)</p><p>{</p><p> switch (eventWin)<br /> {<br /> case EVENT_SYSTEM_SWITCHSTART:<br /> TRACE0("[EVENT_SYSTEM_MENUSTART] "); // Alt +Tab 被按下<br /> break;<br /> case EVENT_SYSTEM_SWITCHEND:<br /> TRACE0("[EVENT_SYSTEM_MENUEND] "); // Alt +Tab 被鬆開<br /> break;<br /> }<br /> TRACE1("hwnd=0x%.8x/n", hwnd);</p><p>}</p><p>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.