I want to check if the system has a battery or not and then get the percentage of battery remaining. I'm not sure how to check if a battery exists, but Here is the code I tried to get the percentage of battery remaining which doesn't work since The code only returns 0:
public double GetBatteryPercent()
{
ManagementClass wmi = new ManagementClass("Win32_Battery");
ManagementObjectCollection allBatteries = wmi.GetInstances();
double batteryLevel = 0;
foreach (var battery in allBatteries)
{
batteryLevel = Convert.ToDouble(battery["EstimatedChargeRemaining"]);
}
return batteryLevel;
}
Also I'm using visual studio 2015 on windows 7 could that be the potential problem that's causing this?
I hope you're testing your code on a system that has a battery indeed. After running this code I see that my system has 1 battery and
batteryLevel
variable was set to the percentage reported by Windows.From what you have described, and after reading your code I assume that you either have 0 batteries or have more than one battery and the last one in the
allBatteries
collection has the level of 0%, hence the return value. Have a good look at your code - you traverse through all the objects inallBatteries
but take only the last one as return value.What you can do is
batteryLevel
to -1 so you know whether the loop over theallBatteries
was run (i.e.allBatteries
had any items at all)