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. I’m sure there’s some way to find out the battery’s status buried somewhere in Windows but I haven’t found it yet.

Fortunately it’s easy to get this 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";
        txtFullLifetime.Text =
    txtCharge.Text = status.BatteryLifePercent.ToString("P0");
    if (status.BatteryLifeRemaining == -1)
        txtLifeRemaining.Text = "Unknown";
        txtLifeRemaining.Text =
    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 there.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in system and tagged , , , , , , , , . Bookmark the permalink.