I have found the foreground window on my desktop using the GetForegroundWindow() function. I need to keep track of how much time each application spends in the foreground and update it in the database each time in resumes to the foreground.
Is there an API to set the counter or find when the window is not in focus?
I have found the foreground window on my desktop using the GetForegroundWindow() function. I
Share
There is
WH_CBThook type supported bySetWindowsHookEx, which fires every time user switches to another window or application. How to install Windows hooks from C#.However, if you don’t need perfect accuracy, it’s much easier to just call
GetForegroundWindow()once per second and check if the numerical value of the returnedHWNDhas changed. For something like an activity tracker app which does not need to notice half-a-second intervals this technique is a better choice.Tips:
GetForegroundWindow()returns the handle of the window that is currently in focus (which can be desktop or taskbar or floating widget so you may need to filter that), or zero handle if there is no window currently focused.