C#, Constantly monitor battery level

2019-06-22 08:57发布

问题:

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.

回答1:

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
         }
    }
}

Check here for more.



回答2:

While loop will cause your UI to response poor and the application will get crashed. You can solve this by using many ways. Please check out the below code snippet will help your needs.

public delegate void DoAsync();

private void button1_Click(object sender, EventArgs e)
{
   DoAsync async = new DoAsync(GetBatteryDetails);
   async.BeginInvoke(null, null);
}

public void GetBatteryDetails()
{
   int i = 0;
   PowerStatus ps = SystemInformation.PowerStatus;
   while (true)
   {
     if (this.InvokeRequired)
         this.Invoke(new Action(() => this.Text = ps.BatteryLifePercent.ToString() + i.ToString()));
     else
         this.Text = ps.BatteryLifePercent.ToString() + i.ToString();

     i++;
   }
}


回答3:

BatteryChargeStatus.Text =  SystemInformation.PowerStatus.BatteryChargeStatus.ToString(); 
BatteryFullLifetime.Text  = SystemInformation.PowerStatus.BatteryFullLifetime.ToString();
BatteryLifePercent.Text  = SystemInformation.PowerStatus.BatteryLifePercent.ToString();
BatteryLifeRemaining.Text = SystemInformation.PowerStatus.BatteryLifeRemaining.ToString();
PowerLineStatus.Text = SystemInformation.PowerStatus.PowerLineStatus.ToString();

If you want to perform some operation just convert these string values into the integer.