有没有办法从使用 .NET 在 Windows 上运行的所有应用程序中捕获所有键盘和鼠标事件?
我找到了一些类似的帖子,第一个是如何为您正在开发的应用程序执行此操作: VB检测空闲时间
以及显示如何查找桌面空闲时间的帖子:检查用户是否处于非活动状态
我尝试的内容如下,基本上在我的主窗体中使用了一个计时器,每 10 秒调用一次 GetInactiveTime,我记录该时间,然后当 CurrentInactiveTime
<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环境中编程。
感谢您的帮助。
我已经用这个解决方案解决了同样的问题。这是我在网上找到的代码,但我已经根据我的需求对其进行了调整。
您应该能够将其放入代码窗口中,并根据需要对其进行修改。
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