How do I check if a battery exists on the system and then get the battery percentage in C# for my WPF application

525 views Asked by At

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?

1

There are 1 answers

1
Mike On BEST ANSWER

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 in allBatteries but take only the last one as return value.

What you can do is

  • set the initial batteryLevel to -1 so you know whether the loop over the allBatteries was run (i.e. allBatteries had any items at all)
  • return a nullable array of battery levels - if it is null it means there are no batteries installed, otherwise you can calculate the average to have the actual battery level
  • even better - return nullable dictionary of battery level and battery capacity so later on you can calculate weighted average of all batteries level (null for the same indication as above)