C# – Auto restart application after given idle time

What would you do if you want to restart your application after given idle time or log out your users out of your system. Surely you’ll think of setting a timer and process its Tick function to calculate the idle time and then take appropriate processing steps. So I would like to introduce a built-in Windows API function which gives us the last time when the user does something on our application. This API is called GetLastInputInfo. The GetLastInputInfo function retrieves the time of the last input event. This function is useful for input idle detection. However, GetLastInputInfo does not provide system-wide user input information across all running sessions. Rather, GetLastInputInfo provides session-specific user input information for only the session that invoked the function. You’ll need Windows 2000 as minimum OS to use it.
The following code snippet shows a small demonstration how this API works in C# format. First, you need to declare its signature

[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

The struct LASTINPUTINFO has following structure. It contains the time of the last input. cbSize must be set to sizeof(LASTINPUTINFO) and dwTime is the tick count when the last input event was received.

[StructLayout( LayoutKind.Sequential )]
struct LASTINPUTINFO
{
	public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));

	[MarshalAs(UnmanagedType.U4)]
	public int cbSize;
	[MarshalAs(UnmanagedType.U4)]
	public UInt32 dwTime;
}   

And now we tinker them together to archive a working code.

static int GetLastInputTime()
{
	int nIdleTime = 0;
	LASTINPUTINFO liiInfo = new LASTINPUTINFO();
	liiInfo.cbSize = Marshal.SizeOf(liiInfo);
	liiInfo.dwTime = 0;
	int nEnvTicks = Environment.TickCount;
	if (GetLastInputInfo(ref liiInfo))
	{
		int nLastInputTick = liiInfo.dwTime;
		nIdleTime = nEnvTicks - nLastInputTick;
	}
	return ((nIdleTime > 0) ? (nIdleTime / 1000) : nIdleTime);
}  

The result of this function gives idle time in seconds. You should convert it to appropriate time format which you need and to restart you application call simply “Form.Restart” in your code. As you can see, the more we know about OS, the little code we must write and therefore we have more time to enjoy our life.