VB检测空闲时间 [英] VB Detect Idle time

查看:176
本文介绍了VB检测空闲时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来检测用户是否闲置了5分钟,然后执行某项操作,并且如果他何时回来,该操作将停止,例如计时器.

I'm looking for a way to detect if the user has been idle for 5 min then do something, and if and when he comes back that thing will stop, for example a timer.

这是我尝试过的方法(但这只会检测到form1是否处于非活动状态/未被单击或其他任何内容):

This is what i have tried (but this will only detect if form1 has been inactive / not clicked or anything):

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接口.它使您可以在发送输入消息之前对其进行嗅探.看到用户正在操作鼠标或键盘时,请重新启动计时器.

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.

在主窗体上放置一个计时器,并将Interval属性设置为超时.从2000开始,因此您可以看到它的工作原理.然后使您的主表单中的代码如下所示:

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

如果显示未用.NET代码实现的任何模式对话框,则可能必须添加临时禁用计时器的代码.

You may have to add code that disables the timer temporarily if you display any modal dialogs that are not implemented in .NET code.

这篇关于VB检测空闲时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆