Today
Today

Reputation: 13

How to keep track of the time duration that a foreground application is active

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?

Upvotes: 1

Views: 869

Answers (2)

hamstergene
hamstergene

Reputation: 24439

There is WH_CBT hook type supported by SetWindowsHookEx, 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 returned HWND has 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.
  • It is ultra-fast so there is no harm in calling it tens or hundreds times a second.
  • Window handle values are unique (at least in the current user session), different even when they belong to different applications, and they are assigned in a way that a destroyed handle is almost never immediately reassigned.

Upvotes: 1

Ajay
Ajay

Reputation: 18441

If you are concerned about your own application, you may handle Activate/Focus/LostFocus/DeActivate events. If you need to monitor all windows, you need to use Windows Hooks for this. One article here.

Upvotes: 0

Related Questions