我正在寻找一种方法来检测用户是否已经闲置了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
答案 0 :(得分:14)
通过在主窗体中实现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代码中实现的模式对话框,则可能必须添加暂时禁用计时器的代码。