static void RecordApplications()
{
while (!STOP)
{
try
{
//get the process window name and exe name
IntPtr tempWin = GetForegroundWindow();
IntPtr win = tempWin;
while (tempWin != IntPtr.Zero && tempWin != desktopWin)
{
win = tempWin;
tempWin = GetAncestor(tempWin, GA_PARENT);
}
StringBuilder sb = new StringBuilder();
GetWindowText(win, sb, 150);
string title = sb.ToString();
if (win != lastWin || title != lastEntry.title)
{
lastWin = win;
if (lastEntry.procName != null)
{
lastEntry.timeSpan = DateTime.Now - lastEntry.dateTime;
WriteLastEntry();
}
uint procId;
GetWindowThreadProcessId(win, out procId);
Process p = Process.GetProcessById((int)procId);
string procName = p.ProcessName;
//now title is the win title and procName is the EXE
lastEntry.dateTime = DateTime.Now;
lastEntry.procName = procName;
lastEntry.title = title;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + Environment.NewLine + "The application will retry..." + Environment.NewLine + ex.StackTrace + Environment.NewLine);
}
finally
{
Thread.Sleep(pollRate);
}
}
}