3

Recently I have been making a program which finds out the battery percentage of the user's computer. I'm trying to figure out which method to use. I've seen there are two ways of doing it such as:

PowerStatus powerStatus = SystemInformation.PowerStatus;
if (powerStatus.BatteryLifePercent < 0.1)
{
    MessageBox.Show("Battery is at 10%");
}

and

ManagementClass wmi = new ManagementClass("Win32_Battery");
var allBatteries = wmi.GetInstances();
foreach (var battery in allBatteries)
{
    int batteryLevel = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
    if (batteryLevel < 10)
    {
        MessageBox.Show("Battery is at 10%");
    }

I'm not sure which method to use.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

2

I have tested both codes on my MSI Laptop. The first one returns 1% in Battery Life Percent.

Both works, as comments bellow (thanks btw) the first one returns a float. so 1 will be 100%.. and 0.1 10%..

Using ManagementClass, I got the correct result, 100%.

I do prefer to sometimes use the Management Class. PowerStatus is only in System.Windows.Forms namespace too.

Thiago Loureiro
  • 1,041
  • 13
  • 24
  • 1
    Are you sure it doesn't return 1 as in 100%? Please see the documentation - this method returns a float, so 1 would be 100%. If this is true this is a bad test and likely a bad answer... https://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.batterylifepercent(v=vs.110).aspx – Maciej Jureczko Sep 02 '17 at 12:49
  • Agreed, i didn't noticed this. tks – Thiago Loureiro Sep 02 '17 at 13:05
2

Both methods are OK, but, please notice that PowerStatus.BatteryLifePercent returned value is float in [0..1.0f] range. So the PowerStatus version should be

if (SystemInformation.PowerStatus.BatteryLifePercent < 0.1) // 0.1 == 10%
  MessageBox.Show("Battery is at 10%");

see

https://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.batterylifepercent(v=vs.110).aspx

for details

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Oh my apologies, I will edit my answer. Thank you for the answer though. –  Sep 02 '17 at 11:59
  • Exactly. That's why @ThiagoLoureiro 's answer is probably not correct. This answer, whilst being a good catch, and an important comment, is still not the answer to the question. The answer should compare the two methods and explain how they differ. – Maciej Jureczko Sep 02 '17 at 12:52