您不想使用计时器来计算正常运行时间。计时器太不可靠了,不能指望它每秒准确地触发一次。因此,您可以使用名为 GetProcessTimes() 的 API 函数:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683223%28v=vs.85%29.aspx
PInvoke 语句是:
[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);
将此语句放在一个类中。
编译器查找这些类型所需的导入如下:
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
using System.Runtime.InteropServices;
将 FILETIME 转换为 DateTime 的函数如下:
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));
}
}
最后,这两个函数的使用示例如下:
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());
}
}