How to detect system idle time

If you want to detect user inactivity even if your application is in background (has no focus), it’s really simple. You can achieve this using GetLastInputInfo function.

This function is a standard Windows API function since Windows 2000 (it means it’s not compatible with Win9x generation). For more info about GetLastInputInfo, visit Microsoft Developer Network.

The function returns the time of last input (keyborad, mouse) in miliseconds. So just compare this value with actual time and you have idle time as result.

Put Label and Timer components on application Form and set OnTimer event as below. Label will show idle time since last input in seconds. Try to move mouse or press some keys to see how detection works.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    Timer1: TTimer;
    Label1: TLabel;
    procedure Timer1Timer(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function IdleTime: DWord;
var
  LastInput: TLastInputInfo;
begin
  LastInput.cbSize := SizeOf(TLastInputInfo);
  GetLastInputInfo(LastInput);
  Result := (GetTickCount - LastInput.dwTime) DIV 1000;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Label1.Caption := Format('System idle time: %d s', [IdleTime]);
end;

end.