Search code examples
c#batterypower-statebatterymanager

Calling PowerStatus.BatteryChargeStatus.ToString() sometimes returns 0


So my method is as follows:

PowerStatus powerStatus = SystemInformation.PowerStatus;

if (powerStatus.BatteryChargeStatus != BatteryChargeStatus.NoSystemBattery)
{
    var batteryStatus = powerStatus.BatteryChargeStatus.ToString()
}

From my test systems I get a wide variety of results such as:

High,

Low,

Charging,

High Charging

Low, Charging

Low, Critical

and heres the strange one... 0?

I'd imagine that it has something to do with BatteryChargeStatus Enum


Solution

  • They missed one. From the docs of the underlying SYSTEM_POWER_STATUS operating system declaration:

    The value is zero if the battery is not being charged and the battery capacity is between low and high

    So just make up your own, like:

        var status = SystemInformation.PowerStatus.BatteryChargeStatus;
        if (status != BatteryChargeStatus.NoSystemBattery) {
            var batteryStatus = status == 0 ? "Not charging" : status.ToString();
            // etc...
        }