Mega Code Archive

 
Categories / Delphi / Examples
 

How to get the battery life

Does your application need to check whether the computer is working off the battery and how much more battery life is left? The API function GetSystemPowerStatus() provides this information. unit BatteryTools; interface function GetBatteryFlag : integer; function GetBatteryLife : integer; function GetBatteryStatus : boolean; implementation uses Windows; // Returns the battery charge status // Results: // 1 - High power // 2 - Low power // 4 - Critical // 8 - Charging // 128 - No status available // 256 - Unknown status function GetBatteryFlag : integer; var Stat: TSystemPowerStatus; begin { GetBatteryFlag } GetSystemPowerStatus(Stat); Result := Stat.BatteryFlag end; { GetBatteryFlag } // Returns the battery life in percent function GetBatteryLife : integer; var Stat: TSystemPowerStatus; begin { GetBatteryLife } GetSystemPowerStatus(Stat); Result := Stat.BatteryLifePercent; if (Result<0) or (Result>100) then Result := -1 end; { GetBatteryLife } // if the AC power status is online true is returned, if offline or unknown then false function GetBatteryStatus : boolean; var iTemp: integer; Stat: TSystemPowerStatus; begin { GetBatteryStatus } GetSystemPowerStatus(Stat); iTemp := Stat.ACLineStatus; Result := iTemp=1 end; { GetBatteryStatus } begin end.