Lenguaje de programación Borland Delphi
A continuación os mostramos tres funciones en Delphi para obtener el estado de carga (en porcentaje, alta, baja, crítica, cargando, no disponible, ...) de la batería de un PC:
// Devuelve el estado de carga de la batería:
// 1 - Alta
// 2 - Baja
// 4 - Crítica
// 8 - Cargando
// 128 - Estado no disponible
// 256 - Estado desconocido
function obtenerEstadoBateria : integer;
var
estado : TSystemPowerStatus;
begin
GetSystemPowerStatus(estado);
Result := estado.BatteryFlag
end;
// Devuelve el estado de carga de la batería (en porcentaje)
function obtenerPorcentajeCarga : integer;
var
estado : TSystemPowerStatus;
begin
GetSystemPowerStatus(estado);
Result := estado.BatteryLifePercent;
if (Result < 0) or (Result > 100) then
Result := -1
end;
// Devuelve los segundos que le quedan de carga a la batería
function obtenerSegundosRestantes : integer;
var
estado : TSystemPowerStatus;
begin
GetSystemPowerStatus(estado);
Result := estado.BatteryLifeTime;
end;
// Si está utilizando la batería devuelve FALSE
// Si no está utilizando la batería o no se sabe el estado devuelve TRUE
function utilizandoBateria : boolean;
var
i : integer;
estado : TSystemPowerStatus;
begin
GetSystemPowerStatus(estado);
i := estado.ACLineStatus;
Result := i = 1
end;
Un ejemplo de utilización:
procedure TformMenuPrincipal.bObtenerEstadoClick(Sender: TObject);
var
porcentajeCarga : integer;
estadoBateria : integer;
segundosRestantes : integer;
horas, minutos, segundos : Integer;
begin
tabEstado.Show;
porcentajeCarga := obtenerPorcentajeCarga;
if porcentajeCarga < 0 then
txtPorcentajeCarga.Text := 'No disponible'
else
txtPorcentajeCarga.Text := IntToStr(porcentajeCarga);
estadoBateria := obtenerEstadoBateria;
case estadoBateria of
1 : txtEstado.Text := 'Alta';
2 : txtEstado.Text := 'Baja';
4 : txtEstado.Text := 'Crítica';
8 : txtEstado.Text := 'Cargando';
128 : txtEstado.Text := 'No disponible';
256 : txtEstado.Text := 'Estado desconocido';
end;
if utilizandoBateria then
txtUtilizandoBateria.Text := 'No'
else
txtUtilizandoBateria.Text := 'Sí';
segundosRestantes := obtenerSegundosRestantes;
if (estadoBateria <> 128) and (estadoBateria <> 256) then
begin
horasMinutosSegundos(segundosRestantes, horas, minutos, segundos);
txtTiempo.Text := format('%02d:%02d:%02d', [horas, minutos, segundos])
end
else
txtTiempo.text := '';
end;
La función utilizada para convertir los segundos en horas, minutos y segundos la puede consultar pulsando aquí
Publicado el: 2005-08-07