Title: Display battery status in C#
Often I'll be working on my laptop when it isn't plugged in and suddenly I get a panicked message from Windows telling me that the battery is almost exhausted and if I don't shut down immediately the world will explode. Fortunately it's easy to get battery status information in C#.
The value SystemInformation.PowerStatus is an object from the PowerStatus class. Its properties give you the information you need. Those properties are:
- BatteryChargeStatus - This enumeration allows a combination of the values Charging, Critical, High, Low, NoSystemBattery, and Unknown.
- BatteryFullLifetime - Gives the number of seconds the battery should last when fully charged.
- BatteryLifePercent - Gives the battery's estimated charge as a percentage between 0.0 and 1.0.
- BatteryLifeRemaining - Gives the estimated number of seconds the battery currently has left.
- PowerLineStatus - This enumeration tells whether the power is connected and can take the values Offline, Online, and Unknown.
This example uses the following code to display the battery properties.
private void ShowPowerStatus()
PowerStatus status = SystemInformation.PowerStatus;
txtChargeStatus.Text = status.BatteryChargeStatus.ToString();
if (status.BatteryFullLifetime == -1)
txtFullLifetime.Text = "Unknown";
txtCharge.Text = status.BatteryLifePercent.ToString("P0");
if (status.BatteryLifeRemaining == -1)
txtLifeRemaining.Text = "Unknown";
txtLineStatus.Text = status.PowerLineStatus.ToString();
This code is straightforward.
On my system the BatteryFullLifetime poroperty consistently returns -1. The BatteryLifeRemaining property returns -1 when the battery is fully charged but returns a value if the computer is unplugged for a while.
If the BatteryLifePercent and BatteryLifeRemaining properties return values, you could calculate an estimate for BatteryFullLifetime, but it probably isn't necessary.
The most important value to the user is undoubtedly BatteryLifeRemaining, and that value seems to always be there.
Download the example to experiment with it and to see additional details.