我希望当用户闲置一段特定时间并且鼠标不在系统上移动而不是从那时开始计算时间时,当用户移动鼠标然后时间停止并且我可以将此时间保存在变量中
答案 0 :(得分:2)
您可以使用GetLastInputInfo API调用。 以下代码主要来自此处:http://pinvoke.net/default.aspx/user32/GetLastInputInfo.html
Imports System.Runtime.InteropServices
Public Class Form1
<StructLayout(LayoutKind.Sequential)> _
Structure LASTINPUTINFO
<MarshalAs(UnmanagedType.U4)> _
Public cbSize As Integer
<MarshalAs(UnmanagedType.U4)> _
Public dwTime As Integer
End Structure
<DllImport("user32.dll")> _
Shared Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
End Function
Dim idletime As Integer
Dim lastInputInf As New LASTINPUTINFO()
Public Function GetLastInputTime() As Integer
idletime = 0
lastInputInf.cbSize = Marshal.SizeOf(lastInputInf)
lastInputInf.dwTime = 0
If GetLastInputInfo(lastInputInf) Then
idletime = Environment.TickCount - lastInputInf.dwTime
End If
If idletime > 0 Then
Return idletime / 1000
Else : Return 0
End If
End Function
Private sumofidletime As TimeSpan = New TimeSpan(0)
Private LastLastIdletime As Integer = 0
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim it As Integer = GetLastInputTime()
If LastLastIdletime > it Then
Label1.Text = "IDLE STATE CHANGED!"
sumofidletime = sumofidletime.Add(TimeSpan.FromSeconds(LastLastIdletime))
Label2.Text = "Sum of idle time: " & sumofidletime.ToString
Else
Label1.Text = GetLastInputTime()
End If
LastLastIdletime = it
End Sub
End Class
此代码显示自每个计时器标记后标签中的最后一个输入操作以来用户空闲的秒数。它还检查空闲状态是否已更改。因此,此时您可以对其做出反应,并将LastLastIdletime
保存为用户处于非活动状态的时间量。
答案 1 :(得分:0)
为了防止必须为许多控件处理这个问题,您可以重新排列一些内容并缓存信息,知道游标是否移动以及空闲时间有多长,为此,您需要一个Point变量和一个Date变量。计时器需要一直打勾。此外,要平衡光标显示/隐藏调用,您需要一个变量来跟踪其可见性状态。以下是完整的代码示例:
Private loc As Point, idle As Date, hidden As Boolean
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If loc <> Cursor.Position Then
If hidden Then
Cursor.Show()
hidden = False
End If
loc = Cursor.Position
idle = Date.Now
ElseIf Not hidden AndAlso (Date.Now - idle).TotalSeconds > 3 Then
Cursor.Hide()
hidden = True
End If
End Sub
此计时器每1 / 2-1秒可以打勾,具体取决于您的响应时间,空闲时间设置为3秒。如果不是问
,那么在阅读代码时应该很容易理解代码并给它一些思考