Wednesday, March 28, 2012

How to detect application idle time

// How To Track Application Idle Time

// Screen shot of the program

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls;

type
  TMainForm = class(TForm)
    Timer1: TTimer;
    Panel1: TPanel;
    procedure Timer1Timer(Sender: TObject);
  private
    { Private declarations }
    function SecondsIdle:DWord;
    function SecToTime(Sec:Integer):string;
  public
    { Public declarations }
  end;

var
  MainForm: TMainForm;

implementation

{$R *.dfm}

{ TMainForm }

// ******************************************************** //
function TMainForm.SecondsIdle: DWord;
// from : http://delphi.about.com/od/adptips2004/a/bltip1104_4.htm
// ******************************************************** //
var
   liInfo: TLastInputInfo;
begin
   liInfo.cbSize := SizeOf(TLastInputInfo) ;
   GetLastInputInfo(liInfo) ;
   Result := (GetTickCount - liInfo.dwTime) DIV 1000;
end;

// ******************************************************** //
function TMainForm.SecToTime(Sec: Integer): string;
// from : http://delphi.about.com/cs/adptips2003/a/bltip0403_5.htm
// ******************************************************** //
var
   H, M, S: string;
   ZH, ZM, ZS: Integer;
begin
   ZH := Sec div 3600;
   ZM := Sec div 60 - ZH * 60;
   ZS := Sec - (ZH * 3600 + ZM * 60) ;
   H := IntToStr(ZH) ;
   M := IntToStr(ZM) ;
   S := IntToStr(ZS) ;
   Result := H + ':' + M + ':' + S;
end;

// ******************************************************** //
procedure TMainForm.Timer1Timer(Sender: TObject);
// ******************************************************** //
begin
  Panel1.Caption:='You are idle for : '+SecToTime(SecondsIdle);
end;

end.