using System; using System.Runtime.InteropServices; namespace IdleDemo { class Program { static void Main(string[] args) { var logoutDuration = TimeSpan.FromSeconds(10); var idle = new IdleUtilities(); var tmr = new System.Timers.Timer(1000); tmr.Elapsed += (s, e) => { var remainingTime = logoutDuration - idle.GetLastInputTime(); var remainingSecond = (int)remainingTime.TotalSeconds; if (remainingSecond <= 0) { Console.WriteLine("Program is closed"); Environment.Exit(0); } else Console.WriteLine($"Program will be closed after {remainingSecond} seconds later"); }; tmr.Start(); Console.WriteLine("Exit?(Y/N)"); do { } while (Console.ReadLine() == "Y"); } } public class IdleUtilities { [StructLayout(LayoutKind.Sequential)] 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")] static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); public TimeSpan GetLastInputTime() { uint idleTicks = 0; var lastInputInfo = new LASTINPUTINFO(); lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo); lastInputInfo.dwTime = 0; uint envTicks = (uint)Environment.TickCount; if (GetLastInputInfo(ref lastInputInfo)) { uint lastInputTick = lastInputInfo.dwTime; idleTicks = envTicks - lastInputTick; } return new TimeSpan(idleTicks * 10000); } } }