C#控制台应用程序计时器

时间:2013-08-08 06:59:46

标签: c# timer

标题说我只想在我的c#游戏模拟器/应用程序中添加一个计时器,并且想要一个计时器来检查这个程序的运行时间,这意味着运行了多长时间但是我希望计时器能够计数而不是所以我可以检查它加载了多少秒。我尝试过很多教程但没有工作,只是错误。

我正在添加计时器并且代码没有显示输入(如果你理解我的意思)一旦我完成输入它们只是错误,下面有红线。

//uptime
        Timer timer = new Timer();
        timer.Interval = 60 * 1000;
        timer.Enabled = true;
        timer.tick();
        timer.Start();

1 个答案:

答案 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());
        }
}