简体   繁体   中英

Total time in foreground for all installed windows application

How can I get the total time this application spent in the foreground, measured in milliseconds? When in the foreground, the user is actively interacting with the application. I need it for all windows installed applications every hour.

The closest solution that I found - https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.totalprocessortime?view=net-5.0 But this solution is per process and without consideration process state (background/foreground)

It sounds like you want to monitor end-user application use. For that I'd recommend a global hook, however, global hooks in.Net are either extremely limited or blocked. Here's a old project that uses a C++ DLL from.Net to create the actual hook: https://www.codeproject.com/articles/6362/global-system-hooks-in-net

I don't think there is a hook for when a Application / Window becomes active though. So what you might want to do is add a Mouse Hook, and then use something likehttp://pinvoke.net/default.aspx/user32/GetForegroundWindow.html to get the handle of the current Active Foreground Window.

Compare that handle to the last handle you retrieve. If different, record a start date/time, and then use other functions get more info about the Window in question (such as Title bar and exe name).

Then every time you detect a change, record a end date/time, calculate the difference between the start / end time, and put that into a Dictionary<Handle, Long> that tracks total ticks for each Handle.

One caveat is Alt+Tab. You might need a keyboard hook as well.


One alternative to maybe check out is this article I found: https://www.c-sharpcorner.com/article/active-application-watcher-in-net-using-windows-forms/

Seems to also be doing what you want, but instead of it being a Mouse / Keyboard hook, it just has a Timer that fires every half second, and grabs the active foreground Window. The downside of that approach is accuracy (course even the hook isn't going to 100% precise).

If you go for the latter, I'd recommend swapping out the Timer control for something else. The System.Windows.Forms.Timer class is not precise - so it might fire every half second, but it might not - especially if the CPU Usage spikes cause of another app. Course other types of Timers are going to have issues with CPU Usage spikes, but Forms.Timer is probably the least precise of all the options available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM