2010. április 27., kedd

Time Out an application


How to apply a time out to prevent user inactivity.


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:

procedure TForm1.ResetTimeElapsed;
  TimeElapsed := 0;

Two event can resume in a sufficient manner the gloabl user activity.

OnKeyDown Event

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
    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.

Nincsenek megjegyzések:

Megjegyzés küldése