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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Vasyl Boroviak
  • 5,959
  • 5
  • 51
  • 70

2 Answers2

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 */
}
DReJ
  • 1,966
  • 15
  • 14
  • 1
    Looks like this is the one I was looking for. Let me check it out. – Vasyl Boroviak Dec 10 '10 at 10:16
  • 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. – DReJ Dec 10 '10 at 10:19
  • 9
    Why is there a C/C++ answer to a C# question? – Chris Oct 22 '15 at 19:52
  • 1
    @Chris Knowing the Win32 call allows you to use p/invoke http://www.pinvoke.net/default.aspx/user32/SetWinEventHook.html – pomeroy Dec 07 '16 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. – Chris Vilches Jun 16 '17 at 23:14
  • (And if someone argues that this is C++, then hEvent has no type, so still pseudo-code) – Chris Vilches Jun 16 '17 at 23:24
  • 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... – Werner Erasmus Oct 19 '17 at 16:07
3

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

Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222