Is there Windows system event on active window changed?

18,432

Solution 1

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 */
}

Solution 2

There's the WM_ACTIVATE message, which is sent to the activated and deactivated windows.

Share:
18,432

Related videos on Youtube

Vasyl Boroviak
Author by

Vasyl Boroviak

Updated on December 11, 2020

Comments

  • Vasyl Boroviak
    Vasyl Boroviak over 3 years

    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.

  • Vasyl Boroviak
    Vasyl Boroviak over 13 years
    This is not the one I'm looking for. In is unreasonable to subscribe to every window in the system. :)
  • Vasyl Boroviak
    Vasyl Boroviak over 13 years
    Looks like this is the one I was looking for. Let me check it out.
  • Piskvor left the building
    Piskvor left the building over 13 years
    @Vasiliy Borovyak: Ah, never mind then - I have misunderstood, thinking you only need the active state of a specific window.
  • DReJ
    DReJ over 13 years
    I have never tried EVENT_SYSTEM_FOREGROUND, but I hooked EVENT_OBJECT_LOCATIONCHANGE event to handle windows position change with SetWinEventHook and it worked fine for me.
  • Chris
    Chris over 8 years
    Why is there a C/C++ answer to a C# question?
  • pomeroy
    pomeroy over 7 years
    @Chris Knowing the Win32 call allows you to use p/invoke pinvoke.net/default.aspx/user32/SetWinEventHook.html
  • Chris Vilches
    Chris Vilches almost 7 years
    Downvote because it's pseudocode. Pretty much nothing, whether it's the method, or those parameters, and not even the "VOID CALLBACK" thing is found by the compiler. Nothing works.
  • Chris Vilches
    Chris Vilches almost 7 years
    (And if someone argues that this is C++, then hEvent has no type, so still pseudo-code)
  • Werner Erasmus
    Werner Erasmus over 6 years
    @DReJ, I've found that this doesn't work consistently. Sometimes my callback is called, other times not, depending from what to what focus is switched. Perhaps another event...