有没有办法从使用.NET的Windows上运行的所有应用程序中捕获所有键盘和鼠标事件?
我发现了一些类似的帖子,第一个是如何为您正在开发的应用程序执行此操作:VB Detect Idle time
以及显示如何查找桌面闲置时间的帖子:Check whether user is inactive
我尝试的是在下面,基本上使用我的主窗体中的计时器每隔10秒调用一次GetInactiveTime并记录该时间,然后当CurrentInactiveTime< LastInactiveTime我举起一个事件。我正在寻找的东西会更实时,更准确。
<StructLayout(LayoutKind.Sequential)> _
Public Structure LASTINPUTINFO
Public cbSize As UInteger
Public dwTime As UInteger
End Structure
<DllImport("user32.dll")> _
Friend Shared Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
End Function
Public Shared Function GetInactiveTime() As TimeSpan
Dim info As LASTINPUTINFO = New LASTINPUTINFO()
info.cbSize = CUInt(Marshal.SizeOf(info))
If GetLastInputInfo(info) Then
Return TimeSpan.FromMilliseconds(Environment.TickCount - info.dwTime)
Else
Return Nothing
End If
End Function
Sub Main()
inactiveTimer = New Timer()
inactiveTimer.Interval = 10000
inactiveTimer.Enabled = True
inactiveTimer.Start()
Dim tempTime As DateTime = Now
lastInactiveTime = tempTime - tempTime
End Sub
Private Sub inactiveTimer_Tick(sender As Object, e As EventArgs) Handles inactiveTimer.Tick
Dim currentInactiveTime As TimeSpan = GetInActiveTime()
Dim tempLastInactiveTime As TimeSpan = lastInactiveTime
lastInactiveTime = currentInactiveTime
If currentInactiveTime < tempLastInactiveTime Then
RaiseEvent SomeEvent
End IF
End Sub
另外,我正在Windows / VB.NET环境中编程。
感谢您的帮助。
答案 0 :(得分:2)
我已经将此解决方案用于同样的问题。这是我在网上找到的代码,但我已经根据我的需要进行了调整。
您应该可以将其放入代码窗口并根据需要进行修改。
Public Structure LASTINPUTINFO
Public cbSize As Int32
Public dwTime As Int32
End Structure
Declare Function GetLastInputInfo Lib "User32.dll" (ByRef plii As LASTINPUTINFO) As Boolean
Private Sub IdleTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IdleTimer.Tick
If ReportingEntireClass = False Then
Dim LII As New LASTINPUTINFO, TicksSinceLastInput As Int32 = 0
LII.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(LII)
If GetLastInputInfo(LII) Then TicksSinceLastInput = (Environment.TickCount - LII.dwTime)
If TicksSinceLastInput >= IdleSeconds Then
If IdleClosing = False Then
IdleClosing = True
Idle.ShowDialog() 'this is a little
'form that warns about the app closing.
End If
End If
End If
End Sub