I do exactly this using P/Invoke to talk to the GetLastInputInfo
API.
Edit: Here's a complete VB.Net program to display the number of milliseconds since the last input event, system-wide. It sleeps for a second before getting the information, so it reports a time of around a thousand milliseconds, assuming you use the mouse or keyboard to run it. :-)
Imports System.Runtime.InteropServices
Module Module1
<StructLayout(LayoutKind.Sequential)> _
Public Structure LASTINPUTINFO
Public Shared ReadOnly SizeOf As Integer = Marshal.SizeOf(GetType(LASTINPUTINFO))
<MarshalAs(UnmanagedType.U4)> _
Public cbSize As Integer
<MarshalAs(UnmanagedType.U4)> _
Public dwTime As Integer
End Structure
<DllImport("user32.dll")> _
Public Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
End Function
Sub Main()
Dim lii As New LASTINPUTINFO()
lii.cbSize = LASTINPUTINFO.SizeOf
lii.dwTime = 0
System.Threading.Thread.Sleep(1000)
GetLastInputInfo(lii)
MsgBox((Environment.TickCount - lii.dwTime).ToString)
End Sub
End Module