Utilizamos cookies propias y de terceros. [Más información sobre las cookies].
Política de cookies
Proyecto AjpdSoft

· Inicio
· Buscar
· Contactar
· Cookies
· Descargas
· Foros
· Historia
· Nosotros
· Temas
· Top 10
· Trucos
· Tutoriales
· Wiki
Código fuente/Source Code en Delphi de AjpdSoft Comprobador estado batería
Lenguaje de programación Borland Delphi


Os mostramos el código fuente/Source Code de la aplicación "AjpdSoft Comprobador estado batería" realizada en Delphi 6. Si eres usuario registrado te puedes descargar el código fuente completo pulsando aquí (si aún no te has registrado puedes hacerlo desde aquí gratuitamente):

unit UnidadMenuPrincipal;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, ExtCtrls, Menus, TrayIcon, ActnList, shellapi;

type
  TformMenuPrincipal = class(TForm)
    temporizador: TTimer;
    PageControl1: TPageControl;
    tabEstado: TTabSheet;
    tabConfiguracion: TTabSheet;
    GroupBox1: TGroupBox;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    txtPorcentajeCarga: TEdit;
    txtEstado: TEdit;
    txtUtilizandoBateria: TEdit;
    GroupBox2: TGroupBox;
    txtSegundos: TEdit;
    Label4: TLabel;
    bObtenerEstado: TButton;
    bCerrar: TButton;
    Label5: TLabel;
    opGuardar: TCheckBox;
    txtFichero: TEdit;
    opAvisar: TCheckBox;
    txtPorcentajeAviso: TEdit;
    Label6: TLabel;
    opMinimizada: TCheckBox;
    dlGuardar: TSaveDialog;
    Label7: TLabel;
    bSeleccionFichero: TButton;
    opAvisarUna: TCheckBox;
    TrayIcon1: TTrayIcon;
    PopupMenu1: TPopupMenu;
    Mostraraplicacin1: TMenuItem;
    Estadocarga1: TMenuItem;
    N1: TMenuItem;
    Cerrar1: TMenuItem;
    Button1: TButton;
    ActionList1: TActionList;
    actOcultar: TAction;
    actMostrarAplicacion: TAction;
    N2: TMenuItem;
    Ocultar1: TMenuItem;
    actCerrar: TAction;
    actEstadoBateria: TAction;
    bp: TProgressBar;
    lInfoPorcentaje: TLabel;
    txtTiempo: TEdit;
    Label8: TLabel;
    txtTiempoCarga: TEdit;
    Label9: TLabel;
    Button2: TButton;
    actAplicarCambios: TAction;
    LWEB: TLabel;
    procedure bSeleccionFicheroClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure temporizadorTimer(Sender: TObject);
    procedure Cerrar1Click(Sender: TObject);
    procedure actOcultarExecute(Sender: TObject);
    procedure actMostrarAplicacionExecute(Sender: TObject);
    procedure actCerrarExecute(Sender: TObject);
    procedure actEstadoBateriaExecute(Sender: TObject);
    procedure actAplicarCambiosExecute(Sender: TObject);
    procedure guardarConfiguracion ();
    procedure LWEBClick(Sender: TObject);
  private
    { Private declarations }
    avisado : boolean;
    ocultada : boolean;
    automatico : boolean;
  public
    { Public declarations }
  end;

var
  formMenuPrincipal: TformMenuPrincipal;

implementation

uses UnidadProcedimientos;

{$R *.dfm}

// Devuelve el estado de carga de la batería: 
// 1 - Alta
// 2 - Baja
// 4 - Crítica
// 8 - Cargando
// 128 - No batería
// 256 - Estado desconocido
function obtenerEstadoBateria : integer;
var
  estado : TSystemPowerStatus;
begin
  GetSystemPowerStatus(estado);
  Result := estado.BatteryFlag
end;

// Devuelve los segundos que le quedan de carga a la batería
function obtenerSegundosParaCarga : integer;
var
  estado : TSystemPowerStatus;
begin
  GetSystemPowerStatus(estado);
  Result := estado.BatteryFullLifeTime;
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;


// 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;


// 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;


procedure TformMenuPrincipal.guardarConfiguracion ();
begin
  esCadINI('Guardar log', 'Ruta fichero', txtFichero.Text);
  esBoolINI('Guardar log', 'Guardar log', opGuardar.Checked);
  esEntINI('Intervalo', 'Segundos', StrToInt(txtSegundos.Text));
  esBoolINI('Avisar', 'Avisar', opAvisar.Checked);
  esBoolINI('Avisar', 'Avisar una vez', opAvisarUna.Checked);
  esEntINI('Avisar', 'Carga inferior a', StrToInt(txtPorcentajeAviso.Text));
  esBoolINI('Al iniciar', 'Ejecutar minimizada', opMinimizada.Checked);
end;

procedure TformMenuPrincipal.bSeleccionFicheroClick(Sender: TObject);
begin
  dlGuardar.Filter := 'Fichero de texto (*.txt)|*.txt|Todos los archivos (*.*)|*.*';
  dlGuardar.Title := 'Fichero estado batería';
  dlGuardar.FileName := 'EstadoBateria';
  dlGuardar.DefaultExt := 'txt';
  if dlGuardar.Execute then
    txtFichero.Text := dlGuardar.FileName;
end;

procedure TformMenuPrincipal.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
  guardarConfiguracion;
end;

procedure TformMenuPrincipal.FormCreate(Sender: TObject);
begin
  avisado := false;
  ocultada := false;
  automatico := false;
  actEstadoBateriaExecute(Self);
  txtFichero.Text := leCadINI('Guardar log', 'Ruta fichero', ChangeFileExt(ParamStr(0), '.txt'));
  opGuardar.Checked := leBoolINI('Guardar log', 'Guardar log', false);
  txtSegundos.Text := inttostr(leEntINI('Intervalo', 'Segundos', 30));
  opAvisar.Checked := leBoolINI('Avisar', 'Avisar', true);
  opAvisarUna.Checked := leBoolINI('Avisar', 'Avisar una vez', false);
  txtPorcentajeAviso.Text := IntToStr (leEntINI('Avisar', 'Carga inferior a', 20));
  opMinimizada.Checked := leBoolINI('Al iniciar', 'Ejecutar minimizada', false);
  actAplicarCambiosExecute(Self);
  if opMinimizada.Checked then
    actOcultarExecute(Self);
end;

procedure TformMenuPrincipal.temporizadorTimer(Sender: TObject);
var
  porcentaje, porcAviso : integer;
  fichero : TStringList;
begin
  automatico := true;
  actEstadoBateriaExecute(Self);
  automatico := false;
  try
    if opAvisar.Checked then
    begin
      porcentaje := obtenerPorcentajeCarga;
      if not opAvisarUna.Checked or (not avisado and opAvisarUna.Checked) then
      begin
        if (txtPorcentajeAviso.Text <> '') and (txtPorcentajeAviso.Text <> '0') then
        begin
          porcAviso := StrToInt (txtPorcentajeAviso.Text);
          if (porcentaje < porcAviso) and (porcentaje > 0) then
          begin
            MessageDlg('Atención: el estado de carga de su batería es de: ' +
                inttostr(porcentaje) + '%' + chr(13) + chr(13) +
                '¡¡¡¡ GUARDE TODOS LOS DOCUMENTOS ABIERTOS !!!!', mtWarning, [mbok], 0);
            avisado := true;
          end;
        end;
      end;
    end;
    if opGuardar.Checked then
    begin
      fichero := TStringList.Create;
      if FileExists(txtFichero.Text) then
        fichero.LoadFromFile(txtFichero.Text);
      fichero.Add(DateTimeToStr(Now) + ' Estado de carga (porcentaje): ' + txtPorcentajeCarga.Text);
      fichero.SaveToFile(txtFichero.Text);
    end;
  except
  end;
end;

procedure TformMenuPrincipal.Cerrar1Click(Sender: TObject);
begin
  close;
end;

procedure TformMenuPrincipal.actOcultarExecute(Sender: TObject);
var
  porcentajeCarga : integer;
begin
  ocultada := true;
  Hide;
  Application.ShowMainForm := False;
  porcentajeCarga := obtenerPorcentajeCarga;
  if porcentajeCarga > 0 then
    TrayIcon1.Hint := 'AjpdSoft Comprobador estado batería' + chr(13) +
        'Porcentaje: ' + inttostr(obtenerPorcentajeCarga)
  else
    TrayIcon1.Hint := 'AjpdSoft Comprobador estado batería' + chr(13) +
        'Este PC no usa baterías';
  TrayIcon1.Show;
  actOcultar.Visible := false;
  actMostrarAplicacion.Visible := true;
end;

procedure TformMenuPrincipal.actMostrarAplicacionExecute(Sender: TObject);
begin
  ocultada := false;
  show;
  WindowState := wsNormal;
  actOcultar.Visible := true;
  actMostrarAplicacion.Visible := false;
  TrayIcon1.Hide;
end;

procedure TformMenuPrincipal.actCerrarExecute(Sender: TObject);
begin
 close;
end;

procedure TformMenuPrincipal.actEstadoBateriaExecute(Sender: TObject);
var
  porcentajeCarga : integer;
  estadoBateria : integer;
  segundosRestantes : integer;
  horas, minutos, segundos : Integer;
begin
  if ocultada and not automatico then
    actMostrarAplicacionExecute(Self);
  if not automatico then
    tabEstado.Show;
  porcentajeCarga := obtenerPorcentajeCarga;
  if porcentajeCarga < 0 then
  begin
    txtPorcentajeCarga.Text := 'No disponible';
    lInfoPorcentaje.Caption := 'No disponible';
  end
  else
  begin
    txtPorcentajeCarga.Text := IntToStr(porcentajeCarga);
    lInfoPorcentaje.Caption := IntToStr(porcentajeCarga);
    bp.Min := 0;
    bp.Max := 100;
    bp.Position := porcentajeCarga;
    if ocultada then
      TrayIcon1.Hint := 'AjpdSoft Comprobador estado batería' + chr(13) +
        'Porcentaje: ' + inttostr(obtenerPorcentajeCarga);
  end;
  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 hay batería';
    256 : txtEstado.Text := 'Estado desconocido';
  else
    txtEstado.text := '';
  end;
  if utilizandoBateria then
    txtUtilizandoBateria.Text := 'No'
  else
    txtUtilizandoBateria.Text := 'Sí';

  segundosRestantes := obtenerSegundosRestantes;
  if (estadoBateria <> 128) and (estadoBateria <> 256) and (segundosRestantes > 0)  then
  begin
    horasMinutosSegundos(segundosRestantes, horas, minutos, segundos);
    txtTiempo.Text := format('%02d:%02d:%02d', [horas, minutos, segundos])
  end
  else
    txtTiempo.text := '';

  segundosRestantes := obtenerSegundosParaCarga;
  if (estadoBateria <> 128) and (estadoBateria <> 256) and (segundosRestantes > 0)  then
  begin
    horasMinutosSegundos(segundosRestantes, horas, minutos, segundos);
    txtTiempoCarga.Text := format('%02d:%02d:%02d', [horas, minutos, segundos])
  end
  else
    txtTiempoCarga.text := '';
end;

procedure TformMenuPrincipal.actAplicarCambiosExecute(Sender: TObject);
var
  segundos : integer;
begin
  guardarConfiguracion;
  try
    segundos := strtoint(txtSegundos.Text);
    if (segundos > 0) then
    begin
      temporizador.Interval := 1000 * segundos;
      temporizador.Enabled := true;
    end
    else
      temporizador.Enabled := false;
  except
  end;
end;

procedure TformMenuPrincipal.LWEBClick(Sender: TObject);
begin
  ShellExecute(Handle, Nil, PChar('http://www.ajpdsoft.com'),
      Nil, Nil, SW_SHOWNORMAL);
end;

end.
A continuación el código fuente de la unidad "UnidadProcedimientos.pas":
unit UnidadProcedimientos;

interface

uses inifiles, sysutils;

function leBoolINI (clave, cadena : string; defecto : boolean) : boolean;
function leEntINI (clave, cadena : string; defecto : integer) : integer;
function leCadINI (clave, cadena : string; defecto : string) : string;
procedure esBoolINI (clave, cadena : string; valor : boolean);
procedure esEntINI (clave, cadena : string; valor : integer);
procedure esCadINI (clave, cadena, valor : string);
procedure horasMinutosSegundos (numSegundos : integer; var horas, minutos, segundos : integer);

implementation

//Lee un booleano de un INI
function leBoolINI (clave, cadena : string; defecto : boolean) : boolean;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readbool (clave, cadena, defecto);
  finally
    free;
  end;
end;


//Lee un entero de un INI
function leEntINI (clave, cadena : string; defecto : integer) : integer;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readInteger (clave, cadena, defecto);
  finally
    free;
  end;
end;


//Lee una cadena de texto de un INI
function leCadINI (clave, cadena : string; defecto : string) : string;
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    result := readString (clave, cadena, defecto);
  finally
    free;
  end;
end;

//escribe un Booleano en un INI
procedure esBoolINI (clave, cadena : string; valor : boolean);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeBool (clave, cadena, valor);
  finally
    free;
  end;
end;


//Escribe un entero en un INI
procedure esEntINI (clave, cadena : string; valor : integer);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeInteger (clave, cadena, valor);
  finally
    free;
  end;
end;


//escribe una cadena de texto en un INI
procedure esCadINI (clave, cadena, valor : string);
begin
  with tinifile.create (changefileext(paramstr(0),'.INI')) do
  try
    writeString (clave, cadena, valor);
  finally
    free;
  end;
end;

procedure horasMinutosSegundos (numSegundos : integer; var horas, minutos, segundos : integer);
begin
  horas := numSegundos div 3600;
  minutos := numSegundos div 60 mod 60;
  segundos := numSegundos mod 60;
end;

end.




Publicado el: 2005-08-07

Visita nuestro nuevo sitio web con programas y contenidos actualizados: Proyecto A