4

What is the best way to detect when Windows power state is changing?

I need to preform some actions depending on whether the computer is going to Standby/Hibernate/Shut Down

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Steven
  • 2,148
  • 8
  • 33
  • 50

2 Answers2

6

The SystemEvents.PowerModeChanged event should do what you want

You might also want to check out the SystemInformation.PowerStatus property.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    I looked at the PowerModeChanged by thought that was to do with what was powering the pc. how wrong was I.. – Steven Oct 16 '10 at 12:44
5

If you need a sleep event, this works better:

 private ManagementEventWatcher managementEventWatcher;
    private readonly Dictionary<string, string> powerValues = new Dictionary<string, string>
                         {
                             {"4", "Entering Suspend"},
                             {"7", "Resume from Suspend"},
                             {"10", "Power Status Change"},
                             {"11", "OEM Event"},
                             {"18", "Resume Automatic"}
                         };
    public void InitPowerEvents()
    {
        var q = new WqlEventQuery();
        var scope = new ManagementScope("root\\CIMV2");

        q.EventClassName = "Win32_PowerManagementEvent";
        managementEventWatcher = new ManagementEventWatcher(scope, q);
        managementEventWatcher.EventArrived += PowerEventArrive;
        managementEventWatcher.Start();
    }
    private void PowerEventArrive(object sender, EventArrivedEventArgs e)
    {
        foreach (PropertyData pd in e.NewEvent.Properties)
        {
            if (pd == null || pd.Value == null) continue;
            var name = powerValues.ContainsKey(pd.Value.ToString())
                           ? powerValues[pd.Value.ToString()]
                           : pd.Value.ToString();
            Console.WriteLine("PowerEvent:"+name);
        }
    }
    public void Stop()
    {
        managementEventWatcher.Stop();
    }
Emmanuel
  • 7,574
  • 3
  • 24
  • 22