Pregunta

¿Hay alguna manera de saber cuándo se apagó el sistema por última vez?

Sé que hay una manera de averiguar el último tiempo de arranque usando la propiedad LastBootUpTime en el espacio de nombres Win32_OperatingSystem usando WMI .

¿Hay algo similar para averiguar la última hora de apagado?

Gracias.

¿Fue útil?

Solución

(todo aquí es cortesía del 100% de la respuesta anterior de JDunkerley )

La solución está arriba, pero el enfoque de pasar de una matriz byte a DateTime se puede lograr con menos declaraciones utilizando el BitConverter . Las siguientes seis líneas de código hacen lo mismo y dan el DateTime correcto del registro:

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

Otros consejos

Suponiendo que Windows se apaga sin problemas. Lo almacena en el registro:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\ShutdownTime

Se almacena como una matriz de bytes pero es un FILETIME.

Si bien puede haber una mejor manera, he usado esto antes y creo que funciona:

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

El último tiempo de reinicio se puede encontrar usando este fragmento de código

static void Main(string[] args)
    {          
        TimeSpan t = TimeSpan.FromMilliseconds(System.Environment.TickCount);
        Console.WriteLine( DateTime.Now.Subtract(t));          
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top