How to know when was Windows started or shutdown?
Solution 1:
According to this article you can use WMI to get the last boot date/time.
// define a select query
SelectQuery query =
new SelectQuery(@"SELECT LastBootUpTime FROM Win32_OperatingSystem
WHERE Primary='true'");
// create a new management object searcher and pass it
// the select query
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(query);
// get the datetime value and set the local boot
// time variable to contain that value
foreach(ManagementObject mo in searcher.Get())
{
dtBootTime =
ManagementDateTimeConverter.ToDateTime(
mo.Properties["LastBootUpTime"].Value.ToString());
// display the start time and date
txtDate.Text = dtBootTime.ToLongDateString();
txtTime.Text = dtBootTime.ToLongTimeString();
}
Solution 2:
System.Environment.TickCount
has a 24.8 days limitation.
This is because TickCount
is a millisecond value contained in a signed 32 bits value.
Windows API exposes these two functions:GetTickCount
- returns a 32 bits value - available from Windows 2000GetTickCount64
- returns a 64 bits value - available from Vista/Windows Server 2008
You can use GetTickCount64 this way:
using System.Runtime.InteropServices;
[DllImport("Kernel32.dll")]
static extern long GetTickCount64();
DateTime osStartTime = DateTime.Now - new TimeSpan(10000 * GetTickCount64());