Tuesday, January 12, 2010

Getting idle time of a system in C#

The following C# code will get the idle(no keyboard/mouse activity) time of a system.

[StructLayout(LayoutKind.Sequential)]
public struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
};

[DllImport("USER32.DLL")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO ii);

//Get Idle time as tick counts
public long GetIdleTime()
{
LASTINPUTINFO lastInPut = new LASTINPUTINFO();
lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);

if (GetLastInputInfo(ref lastInPut))
{
long el = lastInPut.dwTime;
long ui = (Environment.TickCount - el);

// Overflow
if (ui < 0)
ui = ui + uint.MaxValue + 1;

return ui;
}
else
{
throw new ApplicationException("Timespan");
}

}

//Get Idle time as TimeSpan object
public TimeSpan GetIdleTimeSpan()
{
return new TimeSpan(GetIdleTime() * 10000);
}

Reference:
http://www.chapleau.info/wiki/Project_ActivityMonitoring

No comments: