Search code examples
c#windowssleepsleep-mode

How to grab last time windows awoke from sleep or hibernate modes?


This question on superuser has some answers. I have looked through all the linked documentation provided, but it is a lot of documentation, and I do not really know what specific call I am looking for...

Essentially what I am trying to do is grab the last time (DateTime or otherwise) that Windows resumed from sleep or hibernate modes.

I also saw this question but I don't want to subscribe to events as the program might not be running when the sleep/resume from sleep occur, or in other words, I might need to check the last sleep resume hours or days after it occurs.


Solution

  • You can obtain this information using the Windows Event Log by looking at the most recent entry in the System log for a source of "Microsoft-Windows-Power-Troubleshooter".

    Here's a sample console app to print out the time that the most recent item was written for that source:

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    
    namespace Demo
    {
        class Program
        {
            static void Main()
            {
                var eventLog = new EventLog("System");
    
                var mostRecentWake =
                    EnumerateLog(eventLog, "Microsoft-Windows-Power-Troubleshooter")
                    .OrderByDescending(item => item.TimeGenerated)
                    .First();
    
                Console.WriteLine(mostRecentWake.TimeGenerated);
            }
    
            public static IEnumerable<EventLogEntry> EnumerateLog(EventLog log, string source)
            {
                foreach (EventLogEntry entry in log.Entries)
                    if (entry.Source == source)
                        yield return entry;
            }
        }
    }
    

    Note that this assumes that the most recent entry will be for a wake, which (from inspection) it should be.

    If you want to be sure that you're checking the correct entries, then you could do the following (but of course this will only work if the message is in English):

    var mostRecentWake =
        EnumerateLog(eventLog, "Microsoft-Windows-Power-Troubleshooter")
        .Where(item => item.Message.StartsWith("The system has returned from a low power state."))
        .OrderByDescending(item => item.TimeGenerated)
        .First();