I have a vb.net winform and I want to know how to add sort of like a session time out to it. For example, I have a varialbe set to 10 min, within that 10 min, if there is no activity (no mouse/no keyboard interaction), I would like to log the user out. Can anyone shine some light on this subject on how to make this work?
-
No user input in your app, or anywhere? – Sam Makin Feb 19 '15 at 13:23
-
Yes, there is user input in my app. – user1884032 Feb 19 '15 at 13:25
3 Answers
First question, why do you want to do in a winform. Such things we generally use in web forms. But even you want to use such things in WinForms you need to use Timer Class
.
Whenever you encounter activity, you can just reset the timer by calling Stop
then immediately calling Start
. Place whatever code you'd like in the Timer's Tick
event (assuming this is a System.Windows.Forms.Timer
) and you'll be all set.
-
so during log in, start the timer based on the variable (10 mins). Whenever there is activity, reset timer by calling stop and then call start again? How do I detect there is activity? Can you please give an example? – user1884032 Feb 19 '15 at 13:21
-
Thanks to both your suggestion. I was able to get this working in my app. – user1884032 Feb 19 '15 at 14:20
-
I'd suggest you use the event Application.Idle
.
No need to P/Invoke.
Public Class Form1
Private WithEvents _timer As Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 10 seconds for testing
Me._timer = New Timer With {.Interval = 10000, .Enabled = True}
AddHandler Application.Idle, AddressOf Me.Application_Idle
End Sub
Private Sub Application_Idle(sender As Object, e As EventArgs)
Me._timer.Stop()
Me._timer.Start()
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles _timer.Tick
Me._timer.Stop()
RemoveHandler Application.Idle, AddressOf Me.Application_Idle
' Do something to log the user out
Me.Close()
End Sub
End Class

- 1,257
- 1
- 9
- 15
-
Sub Timer_Tick gives me a compiler error: Event 'Tick' cannot be found. – pianocomposer Mar 12 '21 at 16:08
-
If you are looking for a way to detect input outside your application Amit's suggestion will not work.
See Detecting idle users in Winforms if that is the case. Calling GetLastInputInfo()
and checking the last input value should give you something to go off.
If you are not worried about the user leaving your application, and getting logged out after not using it, use Amit's way of resetting a timer on the input event.
-
I'm not getting how to set this up. Is there a way you can provide me some sample code of how to implement this? – user1884032 Feb 19 '15 at 13:42
-