2012-11-22 59 views
2

有沒有一種方法可以捕獲所有使用.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環境下編程。

感謝您的幫助。

回答

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