Setting a WinEvent Hook

[This is preliminary documentation and subject to change.]

To set a WinEvent hook, you must register a hook procedure by calling the SetWinEventHook function. This function accepts seven parameters that describe the events you want notifications for, the location of the event hook procedure, and other environment variables. The first two parameters, eventMin and eventMax, are event constant values that inclusively declare the lower and upper events you want notifications about. The third parameter, hmodWinEventProc, accepts a handle to the module that contains an in-context hook procedure—this parameter is ignored if the WINEVENT_INCONTEXT flag isn't specified. The fourth parameter, lpfnWinEventProc, is the address of the function that Active Accessibility will call when any of the requested events occurs. The fifth and sixth parameters, idProcess and idThread, are used to identify the specific process and thread to be monitored; setting these to zero indicates that you want to monitor all processes and threads. The last parameter, dwflags, is a bit field that you can use to specify receiving parameters.

The following code fragment, taken from the inspect.cpp file included with this SDK, removes a preexisting event hook or sets a new one. The new hook procedure is called for a specific event (EVENT_OBJECT_FOCUS), is out-of-context, and applies to all threads and processes.

// Set up an event hook.
  hEventHook = SetWinEventHook(EVENT_MIN,         // We want all events
                               EVENT_MAX,
                               GetModuleHandle(NULL),// Use this module
                               WinEventProc,
                               0,        // All processes
                               0,        // All threads
                               WINEVENT_OUTOFCONTEXT);
    // Did we install correctly? 

    if (hEventHook)
        return(TRUE);

    // Did not install properly - fail
    return(FALSE);
 

For more information, see WinEvents and About the WinEventProc Callback Function.