Mega Code Archive

 
Categories / Delphi / Examples
 

Time Out an application

Title: Time Out an application Question: How to apply a time out to prevent user inactivity. Answer: 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: procedure TForm1.ResetTimeElapsed; begin TimeElapsed := 0; end; 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); begin ResetTimeElapsed; end; procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin ResetTimeElapsed; 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. procedure TForm1.Timer1Timer(Sender: TObject); begin Inc(TimeElapsed); if TimeElapsed = MaxTimeOutValue then begin Timer1.Enabled := False; Close; end; 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.