VB Detect Idle time

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.

Leave a Comment