C#, Constantly monitor battery level

Trontor picture Trontor · Jul 24, 2013 · Viewed 9.1k times · Source

I am designing a program that depends on monitoring the battery level of the computer.

This is the C# code I am using:

   PowerStatus pw = SystemInformation.PowerStatus;

   if (pw.BatteryLifeRemaining >= 75)
   {
       //Do stuff here
   }

My failed attempt of the while statement, it uses all the CPU which is undesirable.

    int i = 1;
    while (i == 1)
    {
        if (pw.BatteryLifeRemaining >= 75)
        {
           //Do stuff here
        }
    }

How do I monitor this constantly with an infinite loop so that when it reaches 75% it will execute some code.

Answer

A.Mokhtari picture A.Mokhtari · Jul 24, 2013

Try Timer:

public class Monitoring
{
    System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();

    public Monitoring()
    {
        timer1.Interval = 1000; //Period of Tick
        timer1.Tick += timer1_Tick;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        CheckBatteryStatus(); 
    }
    private void CheckBatteryStatus()
    {
        PowerStatus pw = SystemInformation.PowerStatus;

        if (pw.BatteryLifeRemaining >= 75)
        {
            //Do stuff here
        }
    }
}

UPDATE:

There is another way to do your task complete. You can use SystemEvents.PowerModeChanged. Call it and wait for changes, monitor the changes occured then do your stuff.

static void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
{
    if (e.Mode == Microsoft.Win32.PowerModes.StatusChange)
    {
         if (pw.BatteryLifeRemaining >= 75)
         {
          //Do stuff here
         }
    }
}