Author:水如烟
示例
Public Class Form1
Private WithEvents watcher As New LzmTW.uSystem.LastInputWatcher
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
watcher.TimerInterval = 100
watcher.Start()
End Sub
Private Sub watcher_FreeTicks(ByVal ticks As Long) Handles watcher.FreeTicks
Me.Text = String.Format("空闲时间 {0}", TimeSpan.FromMilliseconds(ticks).ToString)
End Sub
End Class
代码
Imports System.Runtime.InteropServices
Namespace LzmTW.uSystem
''' <summary>
''' 监视Window键盘鼠标空闲时间
''' </summary>
''' <remarks></remarks>
Public Class LastInputWatcher
Implements IDisposable
''' <param name="ticks">距上次活动结束后的空闲时间。毫秒单位</param>
Public Event FreeTicks(ByVal ticks As Long)
Private WithEvents timer As New System.Windows.Forms.Timer
''' <summary>
''' 监视时钟的间隔。毫秒单位
''' </summary>
Public Property TimerInterval() As Integer
Get
Return timer.Interval
End Get
Set(ByVal value As Integer)
timer.Interval = value
End Set
End Property
Public Sub Start()
timer.Start()
End Sub
Public Sub [Stop]()
timer.Stop()
End Sub
Private Sub timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles timer.Tick
RaiseEvent FreeTicks(Win32Native.GetLastInputTime)
End Sub
Private disposedValue As Boolean = False
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
timer.Dispose()
End If
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Private Class Win32Native
Private Sub New()
End Sub
Private Shared pil As LASTINPUTINFO
Shared Sub New()
pil.cbSize = Marshal.SizeOf(pil)
End Sub
<StructLayout(LayoutKind.Sequential)> _
Private Structure LASTINPUTINFO
<MarshalAs(UnmanagedType.U4)> _
Public cbSize As Integer
<MarshalAs(UnmanagedType.U4)> _
Public dwTime As Integer
End Structure
<DllImport("user32.dll")> _
Private Shared Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
End Function
Public Shared Function GetLastInputTime() As Long
If Not GetLastInputInfo(pil) Then Return 0
Return Environment.TickCount - CType(pil.dwTime, Long)
End Function
End Class
End Class
End Namespace
