using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; namespace time_tracker { class Program { [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); [DllImport("user32.dll", SetLastError = true)] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); static void Main(string[] args) { TextWriter outputFile = null; if (args.Length > 0) outputFile = new StreamWriter(args[0], true); string currentProcess = null; DateTime currentBecameForeground = DateTime.Now; while (true) { IntPtr handle = GetForegroundWindow(); StringBuilder desc = new StringBuilder(); int pid = getWindowPID(handle); desc.AppendFormat("{0}, {1}, \"{2}\"", handle, pid, Process.GetProcessById(pid).ProcessName); string text = getWindowText(handle); desc.AppendFormat(", \"{0}\"", text ?? ""); DateTime now = DateTime.Now; now = now.AddMilliseconds(-now.Millisecond); TimeSpan timeSpanAsCurrent = now - currentBecameForeground; string timeAsCurrent = timeSpanAsCurrent.ToString(); if (timeAsCurrent.Contains('.')) timeAsCurrent = timeAsCurrent.Substring(0, timeAsCurrent.LastIndexOf('.')); /*String.Format("{0:2}:{1:2}:{2:2}", (int)timeSpanAsCurrent.TotalHours, timeSpanAsCurrent.Minutes, timeSpanAsCurrent.Seconds);*/ if (desc.ToString() != currentProcess) { if (currentProcess != null) { Console.WriteLine("\r{0}, {1}", timeAsCurrent, currentProcess); if (outputFile != null) { outputFile.WriteLine("{0}, {1}, {2}", now, timeAsCurrent, currentProcess); outputFile.Flush(); } } currentProcess = desc.ToString(); currentBecameForeground = now; } Console.Write("\r{0}, {1}", timeAsCurrent, currentProcess); System.Threading.Thread.Sleep(1000); } } private static int getWindowPID(IntPtr handle) { int pid; GetWindowThreadProcessId(handle, out pid); return pid; } private static string getWindowText(IntPtr handle) { const int nChars = 256; StringBuilder Buff = new StringBuilder(nChars); if (GetWindowText(handle, Buff, nChars) > 0) { return Buff.ToString(); } else { return null; } } } }