2

有没有办法从使用 .NET 的 Windows 上运行的所有应用程序中捕获所有键盘和鼠标事件?

我发现了一些类似的帖子,第一个是如何为您正在开发的应用程序执行此操作:VB Detect Idle time

以及显示如何查找桌面空闲多长时间的帖子:检查用户是否处于非活动状态

我尝试如下,基本上在我的主表单中使用一个计时器,每 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 环境中编程。

谢谢您的帮助。

4

1 回答 1

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
于 2012-11-22T03:10:15.883 回答