window API判斷系統是否為閒置狀態
阿新 • • 發佈:2019-01-02
有時在應用中需要獲取當前的系統狀態,如果閒置一段時間將鎖屏或自動登出。
程式碼示例
可以呼叫GetIdleTime()方法,返回的是毫秒。internal struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } [DllImport("User32.dll")] public static extern bool LockWorkStation(); [DllImport("User32.dll")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO Dummy); [DllImport("Kernel32.dll")] private static extern uint GetLastError(); public static uint GetIdleTime() { LASTINPUTINFO LastUserAction = new LASTINPUTINFO(); LastUserAction.cbSize = (uint)Marshal.SizeOf(LastUserAction); GetLastInputInfo(ref LastUserAction); return ((uint)Environment.TickCount - LastUserAction.dwTime); } public static long GetTickCount() { return Environment.TickCount; } public static long GetLastInputTime() { LASTINPUTINFO LastUserAction = new LASTINPUTINFO(); LastUserAction.cbSize = (uint)Marshal.SizeOf(LastUserAction); if (!GetLastInputInfo(ref LastUserAction)) { throw new Exception(GetLastError().ToString()); } return LastUserAction.dwTime; }