Display a colored battery status in C#


This is a minor update to the example Display battery status in a friendly way in C#. That example periodically checks the battery’s charge. It then draws textual and graphical indicators of the charge and plugged/unplugged status. That example was only for demonstration, so it drew the graphical status in four different ways.

Lately I’ve been breaking in a new laptop battery, so I wanted a way to easily keep track of the battery status. This example draws the graphical status in only one way instead of four. It’s also smaller and changes the colors of the display depending on the status. For example, as you can see from the picture, if the battery has a very small charge, it draws the charged area in red and the uncharged area in yellow.

The following code shows the part of the program that sets the colors.

// Draw the battery image.
Color bg_color = Color.Transparent;
Color outline_color = Color.Gray;
Color charged_color = Color.LightGreen;
Color uncharged_color = Color.White;
if (percent < 0.15f)
    outline_color = Color.Black;
    charged_color = Color.Red;
    uncharged_color = Color.Yellow;
else if (percent < 0.25f)
    outline_color = Color.Black;
    charged_color = Color.Orange;
picHBattery1.Image = DrawBattery(
    bg_color, outline_color,
    charged_color, uncharged_color,

This code defines several Color variables to store the colors that the program will use to draw the graphical indicator. It then uses if else-if tests to change the colors if necessary. The program then calls the DrawBattery method described in the earlier post to draw the battery.

Download the example and see the earlier example to see additional details such as the DrawBattery method.

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 drawing, graphics, system and tagged , , , , , , , , , , . Bookmark the permalink.