Author: Arp Dev
How to apply a time out to prevent user inactivity.
Answer:
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:
1 procedure TForm1.ResetTimeElapsed;
2 begin3 TimeElapsed := 0;
4 end;
Two event can resume in a sufficient manner the gloabl user activity.
OnKeyDown Event
OnMouseMove
When the user do something the TimeElapsed is reset so for the two event the code
will look like this.
5 6 procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
7 Shift: TShiftState);
8 begin9 ResetTimeElapsed;
10 end;
11 12 procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
13 Y: Integer);
14 begin15 ResetTimeElapsed;
16 end;
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.
17 procedure TForm1.Timer1Timer(Sender: TObject);
18 begin19 Inc(TimeElapsed);
20 if TimeElapsed = MaxTimeOutValue then21 begin22 Timer1.Enabled := False;
23 Close;
24 end;
25 end;
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.