2012-09-28 10 views
5

Sto cercando un modo per rilevare se l'utente è rimasto inattivo per 5 minuti quindi fare qualcosa, e se e quando tornerà quella cosa si fermerà, ad esempio un timer.VB Detect Tempo di inattività

questo è quello che ho provato (ma questo rileverà solo se form1 è stato inattivo/non cliccato o niente):

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 
+2

Il tuo obiettivo è rilevare attività tastiera/mouse al di fuori dell'applicazione? –

+1

Sì, sì e se non viene rilevata alcuna attività, eseguire un comando // codice –

risposta

10

Questo è fatto più semplice implementando l'interfaccia IMessageFilter nel modulo principale. Ti consente di annusare i messaggi di input prima che vengano inviati. Riavvia un timer quando vedi l'utente che usa il mouse o la tastiera.

Rilasciare un timer nel modulo principale e impostare la proprietà Intervallo sul timeout. Inizia con 2000 così puoi vederlo funzionare. Poi fare il codice nel tuo aspetto principale forma in questo modo:

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 

Potrebbe essere necessario aggiungere il codice che disattiva il timer temporaneamente se si visualizzano le finestre di dialogo modale che non sono implementati nel codice .NET.