2012-09-28 132 views
5

我正在尋找一種方法來檢測用戶是否已經空閒5分鐘,然後做一些事情,如果當他回來時,那個事情將停止,例如一個計時器。VB檢測空閒時間

這是我曾嘗試(但這隻會檢測是否Form1上一直無所作爲/不點擊或任何東西):

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

您的目標是檢測應用程序之外的鍵盤/鼠標活動嗎? –

+1

是的,如果沒有檢測到任何活動,則運行一個命令//代碼 –

回答

10

這是通過實現在主窗體的IMessageFilter接口完成最簡單的。它可以讓你在發送輸入消息之前嗅探它們。當您看到用戶操作鼠標或鍵盤時重新啓動計時器。

在主窗體上放置一個計時器,並將Interval屬性設置爲超時。從2000年開始,所以你可以看到它的工作。然後使代碼在您的主要形式是這樣的:

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 

您可能需要補充一點,如果你顯示未在.NET代碼實現的任何模式對話框暫時禁止定時器代碼。