Author: Lou Adler
Anyone have suggestions on how to implement an inactivity timer? My application has
passwords for various functions, and I need to be able to automatically logout a
user if they've been inactive for 10 minutes, etc.. I suppose I'd tie into the
messaging queue, looking at keyboard and mouse events. The implementation should
cover activity related to any form in my application, but not any activity outside
the application.
Answer:
In your main form, add the integer variables "ShutdownCounter" and "ShutDownDelay".
Add a TApplicationEvents and a TTimer control. Set the timer interval to, say, 5000
mSecs. In the form's OnCreate event handler, add:
1 { ... }
2 {Set up the automatic log off routine. Get the users auto logoff time,
3 which defaults to 20 minutes. 0 is never autologoff}
4 shutDownDelay := UserIni.ReadInteger('Settings', 'Auto Shutdown Delay', 20);
5 shutDownDelay := shutDownDelay * 60;
6 ShutdownCounter := 0;
7 if shutDownDelay > 0 then
8 timShutDown.Enabled := true;
9 {Enable the timer if you want to use a timeout for this user}
This format allows you to add different logoff times for different users, or
completely disable autologoff - I do this on my development system.
In the TApplicationEvents OnMessage event handler, add code to check for
keypresses, or left mouse button clicks (or any other message you want to use to
keep the app running). Whenever any of these messages are received by the
application, reset the ShutDownCounter to zero.
10
11 procedure TfrmAutoProMain.ApplicationEvents1Message(var Msg: tagMSG;
12 var Handled: Boolean);
13 begin
14 case Msg.message of
15 WM_KEYDOWN, WM_LBUTTONDOWN:
16 ShutdownCounter := 0;
17 end;
18 end;
In the TTimer OnTimer event handler, add code to compare the current value of
ShutDownCounter against the ShutDownDelay for this user. If the counter is larger
than the delay, then we need to exit the application. In my apps, I actually show
another window with a 30 second decrementing progress bar which gives the user
notification that the app is about to shutdown, and gives him a chance to keep the
app alive - that's the references to dlgAutoLogOff .
19
20 procedure TfrmAutoProMain.timShutDownTimer(Sender: TObject);
21 begin
22 Inc(ShutdownCounter, 5);
23 {Increase counter by 5 seconds (if TTimer interval was 5000)}
24 if ShutdownCounter >= shutDownDelay then
25 begin
26 timShutDown.Enabled := false;
27 {The next block handles a "last chance" warning dialog to allow the user
28 to stay alive}
29 dlgAutoLogOff := TdlgAutoLogOff.Create(self);
30 try
31 dlgAutoLogOff.Show;
32 repeat
33 Application.ProcessMessages;
34 until
35 (dlgAutoLogOff.ModalResult = mrOK) or (dlgAutoLogOff.ModalResult = mrAbort);
36 if dlgAutoLogOff.ModalResult = mrOK then
37 begin
38 ShutdownCounter := 0;
39 timShutDown.Enabled := true;
40 end
41 else
42 Application.Terminate;
43 finally
44 dlgAutoLogOff.Free;
45 end;
46 end;
47 end;
|