A few days back i got the idea of figuring our how much time was i spending on different application while working. So i made this small console application its not perfect but it can give you a head start. So i am using the following three classes there is no complex code but still i will try to explain it.
In this test app i am only five applications so the moment it collects the data for five applications it will exit but you can always extend it.
class Program { static void Main(string[] args) { ActiveApplicationPropertyThread activeWorker = new ActiveApplicationPropertyThread(); Thread activeThread = new Thread(activeWorker.StartThread ); activeThread.Start(); Dictionary<string, Double> temp; while(true) { Console.WriteLine(activeWorker.AppInfo); if (activeWorker.activeApplicationInfomationCollector._focusedApplication.Keys.Count > 5) { temp = activeWorker.activeApplicationInfomationCollector._focusedApplication; break; } Thread.Sleep(1000); } foreach (var j in temp.Keys) { Console.WriteLine(j + " " + temp[j] / 1000); } } }
This is the main thread that is monitoring the application and checking if thee application is started and if it is it will log it and start a time against it.
public class ActiveApplicationPropertyThread { private bool _stopThread = true; private string _appName = "Idle"; [DllImport("user32.dll")] static extern int GetForegroundWindow(); [DllImport("user32")] private static extern UInt32 GetWindowThreadProcessId(Int32 hWnd, out Int32 lpdwProcessId); public ActiveApplicationInfomationCollector activeApplicationInfomationCollector; private string _justSentApplicationName = ""; public ActiveApplicationPropertyThread() { activeApplicationInfomationCollector = new ActiveApplicationInfomationCollector(); } public void StopThread() { _stopThread = false; } public void StartThread() { while(_stopThread) { ActiveAppName(); if(_justSentApplicationName == "") { _justSentApplicationName = _appName; activeApplicationInfomationCollector.ApplicationFocusStart(_appName); } if(_justSentApplicationName != _appName ) { activeApplicationInfomationCollector.ApplicationFocusEnd(_justSentApplicationName); activeApplicationInfomationCollector.ApplicationFocusStart(_appName); _justSentApplicationName = _appName; } Thread.Sleep(2000); } } public string AppInfo { get { return _appName; } } private Int32 GetWindowProcessID(Int32 hwnd) { Int32 pid = 1; GetWindowThreadProcessId(hwnd, out pid); return pid; } private void ActiveAppName() { Int32 hwnd = 0; hwnd = GetForegroundWindow(); try { _appName = Process.GetProcessById(GetWindowProcessID(hwnd)).MainModule.ModuleName; }catch(Exception e) { } } }
This helper class is just collecting data for different application and adding the total time being used.