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.
Related videos on Youtube
Author by
Vasyl Boroviak
Updated on December 11, 2020Comments
-
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 (ofuser32.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.
-
angularsen over 11 yearsA very good answer is here: stackoverflow.com/a/11943387/134761
-
-
Vasyl Boroviak over 13 yearsThis is not the one I'm looking for. In is unreasonable to subscribe to every window in the system. :)
-
Vasyl Boroviak over 13 yearsLooks like this is the one I was looking for. Let me check it out.
-
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 over 13 yearsI 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 over 8 yearsWhy is there a C/C++ answer to a C# question?
-
pomeroy over 7 years@Chris Knowing the Win32 call allows you to use p/invoke pinvoke.net/default.aspx/user32/SetWinEventHook.html
-
Chris Vilches almost 7 yearsDownvote 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 almost 7 years(And if someone argues that this is C++, then hEvent has no type, so still pseudo-code)
-
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...