Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, Constantly monitor battery level

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.

like image 988
Trontor Avatar asked Jul 24 '13 11:07

Trontor


1 Answers

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
         }
    }
}
like image 115
A.Mokhtari Avatar answered Sep 18 '22 00:09

A.Mokhtari