SysInfo Scenario 3: Monitor Battery Power Status

See Also

Using just one of the power status properties, you can monitor the charge status of a battery. The BatteryLifePercent property is used to provide a percentage value for a ProgressBar control. A Timer control sets the interval at which the power status is tested.

To create a simple battery meter using the BatteryLifePercent property

  1. Create a new project in Visual Basic.

  2. Add a SysInfo, a Timer, and a ProgressBar control to the form.

  3. Set the Interval property of the Timer control to 5000.

  4. Add the following code to the Timer control’s Timer event:
    Private Sub tmrBattery_Timer()
    If sysBattery.BatteryLifePercent <> 255 Then
    prgBattery.Value =  _ sysBattery.BatteryLifePercent
    prgBattery.Enabled = True
    Else
    prgBattery.Value = 0
    prgBattery.Enabled = False
    End If
    End Sub
    

When the application is run, the SysInfo control queries the operating system for the existence of a battery and then displays its current charge level using the BatteryLifePercent property.

Figure 2.28   A simple battery meter

This example can be enhanced by using one of the power status events to detect when a change occurs to the system’s power status. The following example adds a Label control to the form and uses the PowerStatusChanged event to notify the user when the power status changes.

To update changes to battery power status

  1. Add a Label control to the form.

  2. Add the following code to the Sysinfo control’s PowerStatusChanged event:
    Private Sub sysBattery_PowerStatusChanged()
    Select Case sysBattery.BatteryStatus
    Case 1
    lblStatus.Caption = "Battery OK"
    Case 2
    lblStatus.Caption = "Battery Low"
    Case 4
    lblStatus.Caption = "Battery Critical"
    Case 8
    lblStatus.Caption = "Battery Charging"
    Case 128, 255
    lblStatus.Caption = "No Battery Status"
    End Select
    End Sub
    

Figure 2.29   The battery meter, enhanced with the PowerStatusChanged event

The BatteryStatus property is used in a Select Case statement to return a value that indicates the current battery status setting. Whenever the PowerStatusChange event is fired, the Label control is updated with the current status. For example, if the battery runs down or is removed from the computer.