Is there Windows system event on active window changed?

Vasyl Boroviak picture Vasyl Boroviak · Dec 10, 2010 · Viewed 16.2k times · Source

The desktop application I'm developing need to know what windows were active while the application was run. Currently it performs GetForegroundWindow() call (of user32.dll) every 250 msec. The approach is not very accurate.

Is there any Windows (WINAPI?) event which fires every time the active (focused) window changed? I'd like to subscribe with my callback function.

Thanks.

Answer

DReJ picture DReJ · Dec 10, 2010

Yes, you can use SetWinEventHook function.

hEvent = SetWinEventHook(EVENT_SYSTEM_FOREGROUND , 
    EVENT_SYSTEM_FOREGROUND , NULL, 
    WinEventProcCallback, 0, 0, 
    WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);

.......

VOID CALLBACK WinEventProcCallback ( HWINEVENTHOOK hWinEventHook, DWORD dwEvent, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
    /* your code here */
}