9

我正在寻找一种方法来检测用户是否空闲了 5 分钟然后做一些事情,如果他回来了,那事情就会停止,例如计时器。

这是我尝试过的(但这只会检测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
4

1 回答 1

16

这通过在主窗体中实现 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 代码中实现的模式对话框,您可能必须添加临时禁用计时器的代码。

于 2012-09-28T13:53:35.687 回答