SetWinEventHook不会捕获任何事件

时间:2012-10-17 09:30:10

标签: c++ winapi event-handling event-hooking

这是对此问题的跟进:Alt Tab overlay Win32 identificator

我尝试使用Winuser API中的SetWinEventHook函数捕获alt-tab开关菜单打开(并退出)的时刻。 但是,钩子不会捕获任何事件(例如,最小化窗口),因此,不会调用HandleWinEvent

以下代码受到MSDN page

上提供的代码的极大启发
#ifndef _WIN32_WINNT
    #define _WIN32_WINNT 0x0500
#endif

#ifndef WINVER
    #define WINVER 0x0501
#endif

#include "conio.h"
#include <windows.h>
#include <iostream>


// Global variable.
HWINEVENTHOOK g_hook;

// Prototype
void HandleWinEvent(HWINEVENTHOOK , DWORD , HWND ,
                         LONG , LONG ,
                         DWORD , DWORD );

// Initializes COM and sets up the event hook.
//
void InitializeMSAA()
{
    CoInitialize(NULL);
    g_hook = SetWinEventHook(
        EVENT_MIN ,EVENT_MAX,  // Range of events .
        NULL,                                          // Handle to DLL.
        HandleWinEvent,                                // The callback.
        0, 0,              // Process and thread IDs of interest (0 = all)
        WINEVENT_OUTOFCONTEXT ); // Flags.
}

// Unhooks the event and shuts down COM.
//
void ShutdownMSAA()
{
    UnhookWinEvent(g_hook);
    CoUninitialize();
}

// Callback function that handles events.
//
void HandleWinEvent(HWINEVENTHOOK hook, DWORD event, HWND hwnd,
                         LONG idObject, LONG idChild,
                         DWORD dwEventThread, DWORD dwmsEventTime)
{
    std::cout << std::hex << event ; // desperate attempt to see if any event is caught 

    if (event == EVENT_SYSTEM_SWITCHSTART)
    {
        std::cout << "Begin" ;
    }
    else if (event == EVENT_SYSTEM_SWITCHEND)
    {
        std::cout << "End ";
    }
}



int main()
{
    InitializeMSAA();
    while( getch()!= 'q' ){;}
    ShutdownMSAA();
    return 0;
}

建筑命令:

g++ -o alttab main.cpp -luser32 -lole32

我正在使用Windows XP和MinGW / GCC编译器,版本4.5。

1 个答案:

答案 0 :(得分:4)

从MSDN:调用SetWinEventHook的客户端线程必须具有消息循环才能接收事件。你的主线程等待'q'按钮,没有运行消息循环。