Ashley Smith
Ashley Smith

Reputation: 35

C# Console Application timers

Title says it all i wanted to add a timer into my c# game emulator/application and wanted a timer to check the up time of this program meaning how long it has been running for but i want the timer to count up not down so i can check how many seconds it has been loaded. I have tried many tutorials but none work they just error.

I am adding the timer and the codes are not showing up to type in (if you get what i mean) once ive completed typing them they just error with red lines under them.

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

Upvotes: 0

Views: 3102

Answers (1)

Mark Bertenshaw
Mark Bertenshaw

Reputation: 5689

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

Upvotes: 2

Related Questions