How to get the current battery level in C#


Today I found one blogpost related to how to get laptop battery level. But it was using WMI, and it was slow. Then after searching in MSDN, I found PowerStatus class, which is part of System.Windows.Forms namespace, which can be used to get the battery level. Here is a simple implementation, which shows battery status as well as system connected to AC power.

And here is the code snippet.

PowerStatus p = SystemInformation.PowerStatus;
progressBar1.Value = (int)(p.BatteryLifePercent * 100);
label1.Text = string.Format("{0}%", (p.BatteryLifePercent * 100));
radioButton1.Checked = p.PowerLineStatus == PowerLineStatus.Online;
radioButton2.Checked = p.PowerLineStatus == PowerLineStatus.Offline;
radioButton3.Checked = p.PowerLineStatus == PowerLineStatus.Unknown;

And here is the application running on my laptop

Current Battery Status

Current Battery Status

Happy Coding

Anuraj is currently working as Technical Lead. He is a regular speaker on Technology events. He has more than 11+ years experience with Microsoft.Net Technologies.

Facebook Twitter LinkedIn Google+