C#中,不断地监测电池电量 [英] C#, Constantly monitor battery level
本文介绍了C#中,不断地监测电池电量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我设计这取决于监视计算机的电池电量的程序
I am designing a program that depends on monitoring the battery level of the computer.
这是我使用的C#代码:
This is the C# code I am using:
PowerStatus pw = SystemInformation.PowerStatus;
if (pw.BatteryLifeRemaining >= 75)
{
//Do stuff here
}
我的失败,而
语句的尝试,它使用所有的CPU这是不可取的。
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
}
}
我如何监控这不断地与一个无限循环,这样,当它达到75% 。它会执行一些代码
How do I monitor this constantly with an infinite loop so that when it reaches 75% it will execute some code.
推荐答案
尝试定时器:
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
。
调用它,等待变化,监测变化发生然后做你的东西。
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
}
}
}
这篇关于C#中,不断地监测电池电量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文