我正在添加计时器并且代码没有显示输入(如果你理解我的意思)一旦我完成输入它们只是错误,下面有红线。
//uptime
Timer timer = new Timer();
timer.Interval = 60 * 1000;
timer.Enabled = true;
timer.tick();
timer.Start();
答案 0 :(得分:2)
您不想使用计时器来计算正常运行时间。计时器太不可靠,不能指望它每秒钟都会发射。因此,您可以使用名为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());
}
}