您的位置:首页 > 编程语言

[Windows 编程] 如何截获 Alt+Tab 事件

2009-03-19 09:01 302 查看
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%.8x/n", hwnd);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: