using System; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace TimerApp { public static class NativeMethods { [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); [DllImport("kernel32.dll")] static extern uint GetTickCount(); /// /// 获取系统空闲时间(毫秒) /// /// public static long GetIdleTime() { LASTINPUTINFO lastInputInfo = new LASTINPUTINFO { cbSize = (uint)Marshal.SizeOf(), dwTime = 0 }; if (GetLastInputInfo(ref lastInputInfo)) { uint tickCount = GetTickCount(); uint idleMs = unchecked(tickCount - lastInputInfo.dwTime); return idleMs; } return 0; } static NativeMethods() { } public static void Shutdown() { } } }