C #, constantly monitor the battery level

I am developing a program that depends on controlling the battery level of a computer.

This is the C # code I'm using:

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

My unsuccessful attempt to the while statement, it uses all the unwanted CPUs.

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

How to control this constantly with an infinite loop, so that when it reaches 75%, it will execute some code.

+4
source share
3 answers

Try the 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 accomplish your task. You can use SystemEvents.PowerModeChanged . Name it and wait for the changes, check the changes, then make your own material.

 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.

+9
source

While the loop will cause your user interface to respond poorly and the application will be broken. You can solve this using a variety of methods. Please see the code snippet below to help you.

 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++; } } 
+4
source
 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 ​​to an integer.

+2
source

Source: https://habr.com/ru/post/1493175/


All Articles