title: C# - Raise event on PowerStatus change
body: <p>I've created an application that need to be in a safe state and so I want to follow the power status of the computer in background. If the battery level (if any) is low or critical, I wouldn't allow the user to continue using the application and quit all properly.</p>
  
  <p>First of all, I'm astonished that no such event exists in order to detect the change. You need always to check the PowerStatus manually.</p>
  
  <p>So, I've created a wrapper around it, something like this :</p>
  
  <pre><code>using System;
  using System.Windows.Forms;
  
  namespace MyApp
  {
      internal static class BatteryManagement
      {
          //
          internal static event EventHandler&lt;EventArgs&gt; Changed;
  
          //
          private static bool _started;
          private static System.Threading.Timer _timer;
          private static PowerStatus _previousPowerStatus;
  
          internal static void Start()
          {
              if (!_started)
              {
                  _started = true;
                  ManageBatteryLevel();
              }
          }
  
          internal static void Stop()
          {
              if (_started)
              {
                  if(_timer != null)
                  {
                      _timer.Dispose();
                      _timer = null;
                  }
  
                  _started = false;
              }
          }
  
          private static void ManageBatteryLevel()
          {
              _previousPowerStatus = new PowerStatus();
  
              TimeSpan dueTime = new TimeSpan(0, 0, 0); // Start right now
              TimeSpan period = new TimeSpan(0, 1, 0); // Run every 1 minute
  
              // Setting a timer that launch every period the OnBatteryLevelChange method
              _timer = new System.Threading.Timer(OnBatteryLevelChange, null, dueTime, period);
          }
  
          private static void OnBatteryLevelChange(Object stateInfo)
          {
              PowerStatus powerStatus = new PowerStatus();
  
              if (!_previousPowerStatus.Equals(powerStatus))
              {
                  // Ensure battery level is up to date before raising event
                  _previousPowerStatus = powerStatus;
  
                  if (Changed != null)
                  {
                      Changed(null, EventArgs.Empty);
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>But doesn't work because PowerStatus hasn't any public constructor and I can't store the result of the previous status...</p>
  
  <p>How can I manage this ?</p>
  
  <p>Thanks ...</p>