0

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?

user1884032
  • 337
  • 1
  • 5
  • 18

3 Answers3

2

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
  • Please mark one of the answers as correct, or post your own answer. – Sam Makin Feb 19 '15 at 14:29
1

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
Ripple
  • 1,257
  • 1
  • 9
  • 15
0

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.

Community
  • 1
  • 1
Sam Makin
  • 1,526
  • 8
  • 23