1. Herfried K. Wagner’s VB.Any
  2. .NET
  3. Frequently Asked Questions

Determining the battery status

Determining the battery status
<URL:https://dotnet.currifex.org/dotnet/faqs/systempowerstatus/en/>
----------------------------------------------------------------------------

Determining the battery status

Information about the system power status (battery status) can be obtained
using the 'GetSystemPowerStatus' platform function:

\\\
Imports System.IO
Imports System.Runtime.InteropServices
.
.
.
Private Declare Function GetSystemPowerStatus Lib "kernel32.dll" ( _
    ByRef lpSystemPowerStatus As SYSTEM_POWER_STATUS _
) As Boolean

<StructLayout(LayoutKind.Sequential)> _
Public Structure SYSTEM_POWER_STATUS
    Public ACLineStatus As ACLineStatus
    Public BatteryFlag As BatteryFlag
    Public BatteryLifePercent As Byte
    Public Reserved1 As Byte
    Public BatteryLifeTime As Int32
    Public BatteryFullLifeTime As Int32
End Structure

Public Enum ACLineStatus As Byte
    Offline = 0
    Online = 1
    UnknownStatus = 255
End Enum

<Flags()> _
Public Enum BatteryFlag As Byte
    High = 1
    Low = 2
    Critical = 4
    Charging = 8
    NoSystemBattery = 128
    UnknownStatus = 255
End Enum
.
.
.
Dim sps As SYSTEM_POWER_STATUS
If GetSystemPowerStatus(sps) Then
    Dim sw As New StringWriter()
    With sps
        sw.WriteLine("ACLineStatus: " & .ACLineStatus.ToString())
        sw.WriteLine("BatteryFlag: " & .BatteryFlag.ToString())
        sw.WriteLine( _
            "BatteryLifePercent: " & _
            IIf( _
                .BatteryLifePercent = 255, _
                "Unknown", _
                .BatteryLifePercent.ToString() & " percent" _
            ) _
        )
        sw.WriteLine( _
            "BatteryLifeTime: " & _
            IIf( _
                .BatteryLifeTime = -1, _
                "Unknown", _
                .BatteryLifeTime.ToString() & " seconds" _
            ) _
        )
        sw.WriteLine( _
            "BatteryFullLifeTime: " & _
            IIf( _
                .BatteryFullLifeTime = -1, _
                "Unknown", _
                .BatteryFullLifeTime.ToString() & " seconds" _
            ) _
        )
    End With
    MsgBox(sw.ToString())
Else

    ' An error occured.
End If
///