Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我使用哪种方法来查找C#中的电池百分比?_C# - Fatal编程技术网

我使用哪种方法来查找C#中的电池百分比?

我使用哪种方法来查找C#中的电池百分比?,c#,C#,最近,我一直在做一个程序,找出用户电脑的电池百分比。我在想该用哪种方法。我看到有两种方法可以做到这一点,例如: PowerStatus powerStatus = SystemInformation.PowerStatus; if (powerStatus.BatteryLifePercent < 0.1) { MessageBox.Show("Battery is at 10%"); } PowerStatus PowerStatus=SystemInformation.Pow

最近,我一直在做一个程序,找出用户电脑的电池百分比。我在想该用哪种方法。我看到有两种方法可以做到这一点,例如:

PowerStatus powerStatus = SystemInformation.PowerStatus;
if (powerStatus.BatteryLifePercent < 0.1)
{
    MessageBox.Show("Battery is at 10%");
}
PowerStatus PowerStatus=SystemInformation.PowerStatus;
如果(powerStatus.BatteryLifePercent<0.1)
{
MessageBox.Show(“电池电量为10%”;
}

ManagementClass wmi=新的ManagementClass(“Win32_电池”);
var allbatters=wmi.GetInstances();
foreach(所有电池中的var电池)
{
int batteryLevel=转换为NT32(电池[“估计充电维护]);
如果(电池电平<10)
{
MessageBox.Show(“电池电量为10%”;
}
我不确定使用哪种方法。

我已经在我的MSI笔记本电脑上测试了这两个代码。第一个返回1%的电池寿命百分比

这两种方法都有效,正如下面的评论所说(谢谢你,顺便说一句),第一种方法返回一个float,所以1将是100%,0.110%

使用ManagementClass,我得到了100%的正确结果


有时我确实更喜欢使用管理类。PowerStatus也只在System.Windows.Forms命名空间中。

两种方法都可以,但是请注意,
PowerStatus.BatteryLifePercent
返回值在
[0..1.0f]
范围内浮动。 因此
PowerStatus
版本应该是

if (SystemInformation.PowerStatus.BatteryLifePercent < 0.1) // 0.1 == 10%
  MessageBox.Show("Battery is at 10%");
if(SystemInformation.PowerStatus.BatteryLifePercent<0.1)//0.1==10%
MessageBox.Show(“电池电量为10%”;


详细信息

可能有助于uThanks获得++哦,我很抱歉,我将编辑我的答案。谢谢你的回答。没错。这就是@ThiagoLoureiro的答案可能不正确的原因。这个答案虽然是一个很好的答案,也是一个重要的评论,但仍然不是问题的答案。答案应该比较这两种方法并加以解释它们的区别。你确定它不会像100%那样返回1吗?请参阅文档-此方法返回一个浮点,因此1将是100%。如果这是真的,这是一个糟糕的测试,可能是一个糟糕的答案…同意,我没有注意到这一点。tks
if (SystemInformation.PowerStatus.BatteryLifePercent < 0.1) // 0.1 == 10%
  MessageBox.Show("Battery is at 10%");