vb.net – VB检测空闲时间

前端之家收集整理的这篇文章主要介绍了vb.net – VB检测空闲时间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种方法来检测用户是否已经空闲了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
通过在主窗体中实现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代码中实现的模式对话框,则可能必须添加暂时禁用计时器的代码.

猜你在找的VB相关文章