C#,不断监控电池电量

我正在设计一个依赖于监控计算机电池电量的程序。

这是我使用的C#代码:

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

我失败的while语句尝试,它使用了所有不受欢迎的CPU。

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

如何通过无限循环不断监视它,以便当它达到75%时它将执行一些代码。

试试计时器:

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

更新:

还有另一种方法可以完成任务。 您可以使用SystemEvents.PowerModeChanged 。 调用它并等待更改,监视发生的更改然后执行您的操作。

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

点击这里查看更多信息

虽然循环会导致您的UI响应不佳,应用程序将崩溃。 您可以通过多种方式解决此问题。 请查看以下代码段,以满足您的需求。

 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++; } } 
 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(); 

如果要执行某些操作,只需将这些字符串值转换为整数。