c++winapievent-handlingevent-hooking

SetWinEventHook does not catch any event


It is a follow-up of this question : Alt Tab overlay Win32 identificator.

I try to catch the moment when the alt-tab switch menu open (and exit), using the SetWinEventHook function from the Winuser API. However, the hook do not catch any event (e.g. minimizing a window), and therefore, does not call HandleWinEvent.

The following code is greatly inspired by the one provided on the 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;
}

The building command :

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

I'm using Windows XP with MinGW/GCC compiler, version 4.5.


Solution

  • From MSDN: The client thread that calls SetWinEventHook must have a message loop in order to receive events. Your main thread waits for 'q' button, without running message loop.