Check if user is Idle with C#

GetLastInputInfo function – Retrieves the time of the last input event.

LASTINPUTINFO structure – Contains the time of the last input.

public bool IsUserIdle()
{
	uint idleTime = (uint)Environment.TickCount - GetLastInputEventTickCount();
	idleTime = ((idleTime > 0) ? (idleTime / 1000) : 0);
	//user is idle for 5 min
	return (idleTime >= 5 * 60); 
}
 
private uint GetLastInputEventTickCount()
{
	LASTINPUTINFO lii = new LASTINPUTINFO();
	lii.cbSize = (uint)Marshal.SizeOf(lii);
	lii.dwTime = 0;
 
	return GetLastInputInfo(ref lii) ? lii.dwTime : 0;
}
 
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
	public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
	[MarshalAs(UnmanagedType.U4)]
	public UInt32 cbSize;
	[MarshalAs(UnmanagedType.U4)]
	public UInt32 dwTime;
}
 
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
Categories: C# Tags: , , ,
%d bloggers like this: