 .NET 2.0+Creating a Battery Power Status Monitor
Sometimes programs need to know the power status of a computer. An example is Windows Update, which often requires a computer to be running on mains power before updates are installed. This article explains how to read the power status and battery life.
PowerStatus Class
The .NET framework provides a class named "PowerStatus" that can be used to hold power and battery information for notebook, laptop or tablet computers. This class contains five key properties that can be used when creating a battery power status monitor application:
- BatteryChargeStatus. Returns the battery charging status or named charge level. The charge level is one of High, Low or Critical.
- BatteryFullLifetime. Returns the expected duration of operation, in seconds, that can be achieved from a full battery charge.
- BatteryLifePercent. Returns the percentage of battery life remaining from the current charge.
- BatteryLifeRemaining. Returns the approximate battery life, in seconds, remaining from the current charge.
- PowerLineStatus. Returns the current state of the mains power connection.
In order to query the power and battery status for a computer, a PowerStatus object is required. This can be obtained by querying the static PowerStatus property of the SystemInformation class.
Creating the Application
In this article we will create a Windows Forms application that displays the current power and battery status for the computer. This utility will continuously update the status retrieved from four of the five properties described above.
To begin, create a new Windows Forms application named "BatteryMonitor". The new application will include a blank form with a default name. Change the form name to "BatteryMonitorForm" before continuing.
The Main Form
The battery power monitor program will include a single form to display the current battery and power connection status. The form will include a checkbox to indicate if the mains power is connected, a status bar indicating the percentage of charge remaining and two labels to show the charge time remaining and the current battery status. The form will also include a timer that will be used to automatically refresh the information periodically.
Add the following controls to the form. You may wish to organise these controls into groups in the form or add descriptive labels or a form title. On completing this step, the form should be similar to that shown beneath the table.
| Control Name | Type | Special Properties | Purpose |
|---|
| MainsPower | CheckBox | AutoCheck = False Text = "Running on Mains Power" ThreeState = True | Indicates if the computer is connected to mains power. AutoCheck is disabled so that user clicks are ignored. ThreeState is required as the power status can be Online, Offline or Unknown. Unknown will be represented by a shaded box. | | BatteryIndicator | ProgressBar | Maximum = 100 Minimum = 0 Style = Continuous | Shows a graphical representation of the percentage of battery charge remaining. | | BatteryLifeRemaining | Label | | Shows the estimated remaining battery life in minutes. | | BatteryStatus | Label | | Shows the current status of the battery. | | RefreshTimer | Timer | Interval = 1000 | Causes the refresh of the form data periodically. The Interval of 1000ms indicates a refresh rate of once per second. |

The RefreshStatus Method
The controls on the form will be updated in two different places. When the form is loaded for the first time, the controls will be populated. This will ensure that the controls are never shown with default or empty values that could be misconstrued by a user. Additionally, the timer's Tick event will cause a refresh of the information every second.
To centralise the refreshing, a single method will be created containing the update code. Add the following method declaration to the form's class:
private void RefreshStatus()
{
}
Mains Power Display
The first control to be populated is the checkbox that indicates whether the computer is connected to mains power or is running on a battery. This information will be extracted from the PowerLineStatus property. This property returns a value of the PowerLineStatus enumerated type. The value will be "Online" for mains power, "Offline" for battery power or "Unknown" if the status cannot be determined. A switch statement will be used to react to the three possibilities.
To show the power line status, add the following code to the RefreshStatus method. Note that the first line creates a local variable to contain a reference to the PowerStatus property of the SystemInformation class.
PowerStatus power = SystemInformation.PowerStatus;
switch (power.PowerLineStatus)
{
case PowerLineStatus.Online:
MainsPower.Checked = true;
break;
case PowerLineStatus.Offline:
MainsPower.Checked = false;
break;
case PowerLineStatus.Unknown:
MainsPower.CheckState = CheckState.Indeterminate;
break;
}
Battery Remaining Percentage
The next control to be updated is the progress bar that gives a graphical display of the percentage of battery power remaining. This progress bar will be populated with a value related to that of the BatteryLifePercent property. However, as this property returns a value between zero and one for valid charge percentages, the value will be multiplied by one hundred and cast as an integer.
A check is made before applying the percentage to the progress bar's value. This ensures that the percentage is less than or equal to one hundred. A larger value, specifically 255, indicates that the battery charge information is not available.
Add the following code to the bottom of the RefreshStatus method:
int powerPercent = (int)(power.BatteryLifePercent * 100);
if (powerPercent <= 100)
{
BatteryIndicator.Value = powerPercent;
}
else
{
BatteryIndicator.Value = 0;
}
Battery Time Remaining
The BatteryLifeRemaining property returns the estimated number of seconds before the battery will be exhausted. However, this estimate is not updated constantly by Microsoft Windows. This means that when the mains power is first removed, the property holds -1 to indicate that the time is unavailable. Also, if the time remaining is displayed in seconds, this value will not update constantly and gives the impression of being inaccurate.
To avoid these aesthetic problems, we will check that a positive number of seconds has been returned before showing the value. We will also divide the value by sixty and express the time remaining in minutes. To add this functionality, add the following code to the end of the RefreshStatus method:
int secondsRemaining = power.BatteryLifeRemaining;
if (secondsRemaining >= 0)
{
BatteryLifeRemaining.Text = string.Format("{0} min", secondsRemaining / 60);
}
else
{
BatteryLifeRemaining.Text = string.Empty;
}
Showing the Battery Status
The BatteryChargeStatus property returns a value from the BatteryChargeStatus enumeration. This bit field enumeration has six possible values that sometimes can be combined. The values are:
| Enumeration Constant | Meaning |
|---|
| Charging | The battery is currently being charged. | | Critical | The battery level is below the critical level specified in the user's preferences. | | High | The battery level is high. | | Low | The battery level is low. | | NoSystemBattery | The computer does not have a battery. | | Unknown | The battery status could not be determined. |
As the values can be combined automatically, we will simply convert the property value to a string and assign it to the label's Text property. To do so, add the following code to the foot of the RefreshStatus method:
BatteryStatus.Text = power.BatteryChargeStatus.ToString();
Adding the Form Load Event
On loading the form, two activities must occur. Firstly, the form's controls will be updated to show the current battery and power information. Secondly, the timer will be enabled so that the information is refreshed periodically. Add the form load event to the code and modify it as follows to add these two key activities:
private void BatteryMonitorForm_Load(object sender, EventArgs e)
{
RefreshStatus();
RefreshTimer.Enabled = true;
}
Adding the Timer Event
Finally, the constant updating of power information can be added by calling the RefreshStatus method from within the timer's Tick event. Add this event and modify it as follows:
private void RefreshTimer_Tick(object sender, EventArgs e)
{
RefreshStatus();
}
You can now execute the program to see the results. If you are using a notebook computer, try removing and re-inserting the power cable to see the refreshing in action.
|