システムが最後にシャットダウンされたのはいつかを知る方法はありますか?
WMIを使用してWin32_OperatingSystem名前空間のLastBootUpTimeプロパティを使用して、前回の起動時間を確認する方法があることは知っています。
前回のシャットダウン時間を調べるのに似たものはありますか?
ありがとう。
Windowsがスムーズにシャットダウンされたと仮定します。それはレジストリに保存されます:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\ShutdownTime
これはバイト配列として格納されますが、FILETIME です。
より良い方法があるかもしれませんが、私はこれを以前に使用したことがあり、うまくいくと思います:
public static DateTime GetLastSystemShutdown()
{
string sKey = @"System\CurrentControlSet\Control\Windows";
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sKey);
string sValueName = "ShutdownTime";
object val = key.GetValue(sValueName);
DateTime output = DateTime.MinValue;
if (val is byte[] && ((byte[])val).Length == 8)
{
byte[] bytes = (byte[])val;
System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();
int valLow = bytes[0] + 256 * (bytes[1] + 256 * (bytes[2] + 256 * bytes[3]));
int valTwo = bytes[4] + 256 * (bytes[5] + 256 * (bytes[6] + 256 * bytes[7]));
ft.dwLowDateTime = valLow;
ft.dwHighDateTime = valTwo;
DateTime UTC = DateTime.FromFileTimeUtc((((long) ft.dwHighDateTime) << 32) + ft.dwLowDateTime);
TimeZoneInfo lcl = TimeZoneInfo.Local;
TimeZoneInfo utc = TimeZoneInfo.Utc;
output = TimeZoneInfo.ConvertTime(UTC, utc, lcl);
}
return output;
}
(ここにあるものはすべて、 JDunkerley の以前の回答の100% 礼儀です)
byte
解決策は上にありますが、配列からへのアプローチはDateTime
、BitConverter
.DateTime
public static DateTime GetLastSystemShutdown()
{
string sKey = @"System\CurrentControlSet\Control\Windows";
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sKey);
string sValueName = "ShutdownTime";
byte[] val = (byte[]) key.GetValue(sValueName);
long valueAsLong = BitConverter.ToInt64(val, 0);
return DateTime.FromFileTime(valueAsLong);
}
最後の再起動時間は、このコードを使用して見つけることができます
static void Main(string[] args)
{
TimeSpan t = TimeSpan.FromMilliseconds(System.Environment.TickCount);
Console.WriteLine( DateTime.Now.Subtract(t));
}