You don't want to use a timer to work out uptime. The timer is too unreliable to expect it to fire exactly every second. So it's just as well that there is an API function you can use called GetProcessTimes():
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683223%28v=vs.85%29.aspx
The PInvoke statement is:
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetProcessTimes(IntPtr hProcess, out FILETIME lpCreationTime, out FILETIME lpExitTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
Put this statement inside a class.
The imports you need for the compiler to find these types are as follows:
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
using System.Runtime.InteropServices;
The function to convert FILETIME to DateTime is as follows:
private DateTime FileTimeToDateTime(FILETIME fileTime)
{
ulong high = (ulong)fileTime.dwHighDateTime;
unchecked
{
uint uLow = (uint)fileTime.dwLowDateTime;
high = high << 32;
return DateTime.FromFileTime((long)(high | (ulong)uLow));
}
}
Finally, a sample use of these two functions are as follows:
using System.Diagnostics;
void ShowElapsedTime()
{
FILETIME lpCreationTime;
FILETIME lpExitTime;
FILETIME lpKernelTime;
FILETIME lpUserTime;
if (GetProcessTimes(Process.GetCurrentProcess().Handle, out lpCreationTime, out lpExitTime, out lpKernelTime, out lpUserTime))
{
DateTime creationTime = FileTimeToDateTime(lpCreationTime);
TimeSpan elapsedTime = DateTime.Now.Subtract(creationTime);
MessageBox.Show(elapsedTime.TotalSeconds.ToString());
}
}