Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB Detect Idle time

I'm looking for a way to detect if the user has been idle for 5 min then do something, and if and when he comes back that thing will stop, for example a timer.

This is what i have tried (but this will only detect if form1 has been inactive / not clicked or anything):

Public Class Form1

Private Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'You should have already set the interval in the designer... 
    Timer1.Start()
End Sub

Private Sub form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    Timer1.Stop()
    Timer1.Start()
End Sub


Private Sub form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
    Timer1.Stop()
    Timer1.Start()
End Sub

Private Sub form1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
    Timer1.Stop()
    Timer1.Start()
End Sub

Private Sub Timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    MsgBox("Been idle for to long") 'I just have the program exiting, though you could have it do whatever you want.
End Sub

End Class
like image 428
Johannes Falk Avatar asked Sep 28 '12 09:09

Johannes Falk


People also ask

What is user idle time?

The idle time is the time that the user has no interaction with the web-page. It can be mouse movement, page click or when the user uses the keyboard. The idle time can be detected using either vanilla JavaScript or jQuery code.


1 Answers

This is done easiest by implementing the IMessageFilter interface in your main form. It lets you sniff at input messages before they are dispatched. Restart a timer when you see the user operating the mouse or keyboard.

Drop a timer on the main form and set the Interval property to the timeout. Start with 2000 so you can see it work. Then make the code in your main form look like this:

Public Class Form1
    Implements IMessageFilter

    Public Sub New()
        InitializeComponent()
        Application.AddMessageFilter(Me)
        Timer1.Enabled = True
    End Sub

    Public Function PreFilterMessage(ByRef m As Message) As Boolean Implements IMessageFilter.PreFilterMessage
        '' Retrigger timer on keyboard and mouse messages
        If (m.Msg >= &H100 And m.Msg <= &H109) Or (m.Msg >= &H200 And m.Msg <= &H20E) Then
            Timer1.Stop()
            Timer1.Start()
        End If
    End Function

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Stop()
        MessageBox.Show("Time is up!")
    End Sub
End Class

You may have to add code that disables the timer temporarily if you display any modal dialogs that are not implemented in .NET code.

like image 191
Hans Passant Avatar answered Oct 25 '22 04:10

Hans Passant