In my code I have it laid down like this:
Create a global variable to hold the last recorded tick count IN THE MAIN FORM. At any time that there is any keyboard or mouse activity record the tick count.
Now, periodically check the last tick count against “Now” and if the difference between the two are greater than the period deemed to be a safe idle period, trim the memory.
var
LastTick: DWORD;
Drop an ApplicationEvents component on the main form. In its OnMessage event handler enter the following code:
procedure TMainForm.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean) ;
begin
case Msg.message of
WM_RBUTTONDOWN,
WM_RBUTTONDBLCLK,
WM_LBUTTONDOWN,
WM_LBUTTONDBLCLK,
WM_KEYDOWN:
LastTick := GetTickCount;
end;
end;
Now decide after what period of time you will deem the program to be idle. I decided on two minutes in my case, but you can choose any period you want depending on the circumstances.
Drop a timer on the main form. Set its interval to 30000 (30 seconds) and in its “OnTimer” event put the following one line instruction:
procedure TMainForm.Timer1Timer(Sender: TObject) ;
begin
if (((GetTickCount - LastTick) / 1000) > 120) or (Self.WindowState = wsMinimized) then TrimAppMemorySize;
end;
Adaptation For Long Processes Or Batch Programs
To adapt this method for long processing times or batch processes is quite simple. Normally you’ll have a good idea where a lengthy process will start (eg beginning of a loop reading through millions of database records) and where it will end (end of database read loop).Simply disable your timer at the start of the process, and enable it again at the end of the process.

