WinAPI has a function that does just that: GetLastInputInfo .
This feature is useful for detecting input idle. However, GetLastInputInfo does not provide system-wide user input in all sessions. Rather, GetLastInputInfo provides session input information only for the session that called the function.
And even an example on pinvoke.net . Here is my version:
public static TimeSpan GetIdleTime()
{
var lastInputInfo = new LASTINPUTINFO
{
cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO))
};
if (!GetLastInputInfo(ref lastInputInfo))
throw new Win32Exception("GetLastInputInfo failed");
return TimeSpan.FromMilliseconds(Environment.TickCount - lastInputInfo.dwTime);
}
Relevant definitions for P / Invoke:
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO
{
[MarshalAs(UnmanagedType.U4)]
public UInt32 cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime;
}
source
share