アップタイムを計算するためにタイマーを使用したくありません。タイマーは信頼性が低すぎて、正確に毎秒起動するとは期待できません。したがって、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));
}
}
最後に、これら 2 つの関数の使用例を次に示します。
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());
}
}