27

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.

1

2 Answers 2

33

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 */
}
7
  • 1
    Looks like this is the one I was looking for. Let me check it out. Dec 10, 2010 at 10:16
  • 9
    Why is there a C/C++ answer to a C# question?
    – Chris
    Oct 22, 2015 at 19:52
  • 1
    @Chris Knowing the Win32 call allows you to use p/invoke pinvoke.net/default.aspx/user32/SetWinEventHook.html
    – pomeroy
    Dec 7, 2016 at 22:11
  • 3
    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. Jun 16, 2017 at 23:14
  • 1
    @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... Oct 19, 2017 at 16:07
3

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

2
  • 5
    This is not the one I'm looking for. In is unreasonable to subscribe to every window in the system. :) Dec 10, 2010 at 10:14
  • @Vasiliy Borovyak: Ah, never mind then - I have misunderstood, thinking you only need the active state of a specific window. Dec 10, 2010 at 10:18

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.