Timeout - aplicativo fechar depois de um tempo ocioso
|Top Previous Next|
How to apply a time out to prevent user inactivity.
Here another beginner example
Here a sample code that will allow you to close an application if the user is getting asleep while working / if he go afk for too long.
This can be useful for program like MIRC where they use such Time-Out value. Some online games work like that also to prevent user to take server bandwitch, also coming to my mind are screensaver application or CPU cooler program.
First declare a global constant called MaxTimeOutDelay. Affect it to some integer value that will represent the maximum number of seconds where your program is allowed to record user inactivity before taking action.
Second, declare a variable called TimeElapsed as integer. This will keep track of the time elapsed since user last activity recorded.
Third put a timer on the form.
On the FormCreate event set the TimeElapsed to 0.
Now declare a simple Procedure that will Reset the TimeElapsed.
It should look like:
TimeElapsed := 0;
Two event can resume in a sufficient manner the gloabl user activity.
1 - OnKeyDown Event
2 - OnMouseMove
When the user do something the TimeElapsed is reset so for the two event the code will look like this.
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
Here the last bit of code. On timer event the TimeElapsed is incremented. In short, the Timer Transfer a value to the TimeElapsed variable every second (If you default value for timer wasn't changed).
Than it's just a simple check to see if the TimeElapsed have reached the MaxTimeOutValue.
procedure TForm1.Timer1Timer(Sender: TObject);
if TimeElapsed = MaxTimeOutValue then begin
Timer1.Enabled := False;
This program close the application. But actually it's a lot more useful to associate the TimeOut to a more useful routine. For example you can make the computer sleep when the user didn't do anything for 15 minute, make it run in the system tray to save power/pcu usage.
------------------ COMMENTS -----------------
Maybe a better way (IMHO) would be to have an application Message Handler
Declare a procedure thus:
procedure TForm1.HandleAppMessage(var Msg: TMsg; var Handled: Boolean);
Case msg.Message of
WM_KEYFIRST..WM_KEYLAST, WM_MOUSEFIRST..WM_MOUSELAST: ResetTimeElapsed;
and in FormCreate set
Application.OnMessage := HandleAppMessage;