Tuesday, November 17, 2009

How to get system idle time

If you ever need to get system idle time here are two methods which will be more than helpful.
// retrieves idle time in miliseconds
function GetIdleTime: Cardinal;
const szLastInputInfo = sizeof(TLastInputInfo);
var LastInput: TLastInputInfo;
begin
     LastInput.cbSize := szLastInputInfo;
     GetLastInputInfo(LastInput);
     Result := GetTickCount -LastInput.dwTime;
end;

type TIdleTime = (itWeeks, itDays, itHours, itMin, itSec);

// retrieves idle time in hour, minutes or seconds
function GetIdleTimeEx(IdleTime: TIdleTime): Cardinal;
// because GetIdleTime returns idle time in miliseconds
// we need to transform miliseconds according to our needs
const CIT_SEC = 1000; // 1 miliseconds is 1 second
      CIT_MIN = CIT_SEC * 60; // 60 seconds is 1 minute
      CIT_HOUR = CIT_MIN * 60; // 60 minutes is 1 hour
      CIT_DAYS = CIT_HOUR * 24; // 24 hours is 1 day
      CIT_WEEKS = CIT_DAYS * 7; // 7 days is 1 week
begin
     Result := 0;
     case IdleTime of
          itWeeks: Result := GetIdleTime div CIT_WEEKS;
          itDays: Result := GetIdleTime div CIT_DAYS;
          itHours: Result := GetIdleTime div CIT_HOUR;
          itMin: Result := GetIdleTime div CIT_MIN;
          itSec: Result := GetIdleTime div CIT_SEC;
     end;//case IdleTime of
end;
Usage
ShowMessage(Format('System Idle for %d minute(s)', [GetIdleTimeEx(itMin)]));
If you need to get the idle time in seconds just use itSec in stead of itMin and so on.

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)