How to Display battery status in a friendly way in C# – Programming, Pseudocode Example, C# Programming Example
C# Windows Form

How to Display battery status in a friendly way in C#

The example Display battery status in C# shows how you can get the computer’s battery status. This example shows a couple of different ways you can display the battery’s status in user-friendly ways.

First the program uses the following code to display the status textually.

How to Display battery status in a friendly way in C#
How to Display battery status in a friendly way in C#

This code displays the status in one of the following three easy-to-understand formats:

  • 75 %, charging
  • Online fully charged
  • Offline, 75 % remaining

(UI Tip: This text demonstrates a useful UI principle: Make different things look different. If the first and last messages were “75 %, charging” and “75 % remaining,” then it would be easier to confuse the two. This is probably not the end of the world, but it would make the user waste precious brain cells examining the message more carefully.)

Next the program calls the following DrawBattery method four times to draw the graphical battery representations.

This method creates a bitmap of the desired size. If the width is greater than the height, the method assumes the battery should be drawn horizontally. (You could change that if you wanted to draw a really short fat battery.)

If the battery should be drawn horizontally, the code adds a rotation and translation to the Graphics object so the program can draw the battery vertically. If it should be horizontal, those transformations rotate the result sideways so it comes out correctly.

The method then calls the following DrawVerticalBattery method to draw a vertical battery.

This method calculates a reasonable thickness for the battery’s outline, makes a rectangle to represent the battery’s body area, and creates a thick pen using the desired outline color.

Next the code fills the body area with the “uncharged” color, which is white in this example. The code then fills the part of the body that represents the percent that is charged.

If the striped parameter is true, the code then draws bars through the body representing 25%, 50%, and 75% charges.

1 Comment

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: