[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Display a colored battery status in C#

[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( percent, picHBattery1.ClientSize.Width, picHBattery1.ClientSize.Height, bg_color, outline_color, charged_color, uncharged_color, true);

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 to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.