Tuesday, December 22, 2009

System Idle. Inactivity on C# Sharp.

Today is the day of the user idle time and how can we know when the system is inactive.

Well, first of all we need the user32.dll library and the function GetLastInputInfo. The GetLastInputInfo function retrieves the time of the last input event.
BOOL GetLastInputInfo(
PLASTINPUTINFO plii
);

Where plii is a pointer to
typedef struct tagLASTINPUTINFO {
UINT cbSize;
DWORD dwTime;
} LASTINPUTINFO, *PLASTINPUTINFO;


Now, we can use this information to program in C#.
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

internal struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}

We create an Timer in our Form and set the tick function:
private void Timer_Tick(object sender, EventArgs e)
{
// Get the system uptime
int SystemUptime = Environment.TickCount;
// The tick at which the last input was recorded
int LastInputTicks = 0;
// Ticks since last imput
int IdleTicks = 0;

// Set the struct data
LASTINPUTINFO LastInputInfo = new LASTINPUTINFO();
LastInputInfo.cbSize = (uint)Marshal.SizeOf(LastInputInfo);
LastInputInfo.dwTime = 0;

if (GetLastInputInfo(ref LastInputInfo))
{
// Get the number of ticks
LastInputTicks = (int)LastInputInfo.dwTime;
// Number of idle ticks between SystemUpdate and LastInputTicks
IdleTicks = SystemUptime - LastInputTicks;
}
}

where all this variables are in miliseconds. Now, you can do whatever you want with the variable IdleTicks.

Greetings

No comments:

Post a Comment