If you want to find out how long it has been since the current user no longer made any work (=using the mouse or keyboard), you can use the following code:
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace ConsoleAppUserIdle
{
internal struct LastInput
{
public uint cbSize;
public uint dwTime;
}
public class Win32
{
[DllImport("User32.dll")] private static extern bool GetLastInputInfo(ref LastInput plii);
[DllImport("Kernel32.dll")] private static extern uint GetLastError();
public static uint GetIdleTime()
{
LastInput lastinputinfout = new LastInput();
lastinputinfout.cbSize = (uint)Marshal.SizeOf(lastinputinfout);
GetLastInputInfo(ref lastinputinfout);
return ((uint)Environment.TickCount - lastinputinfout.dwTime);
}
}
class Program
{
static void Main(string[] args)
{
LastInput lastInPut = new LastInput();
lastInPut.cbSize = (uint)Marshal.SizeOf(lastInPut);
uint idleTime;
while (true)
{
Thread.Sleep(100);
Console.Clear();
idleTime = Win32.GetIdleTime();
Console.WriteLine("Last user input: {0} ms ago.", idleTime);
if (idleTime > 10 * 1000)
Environment.Exit(0);
}
}
}
}
This example shows every 100 milliseconds how long the current loged in user has not moved/clicked the mouse or entered a key on the keyboard. If no entry has been registered within 10 seconds, the program simply closes.