且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关闭C#应用程序闲置10分钟后,

更新时间:2023-02-12 07:54:00

您可能需要一些P-调用,具体GetLastInputInfo窗口的功能。它会告诉你什么时候是当前用户检测到的最后一个输入端(键盘,鼠标)。

You might need some p-invoke, specifically GetLastInputInfo windows function. It tells you when was the last input (keyboard, mouse) detected for current user.

internal class Program {
    private static void Main() {
        // don't run timer too often, you just need to detect 10-minutes idle, so running every 5 minutes or so is ok
        var timer = new Timer(_ => {
            var last = new LASTINPUTINFO();
            last.cbSize = (uint)LASTINPUTINFO.SizeOf;
            last.dwTime = 0u;
            if (GetLastInputInfo(ref last)) {
                var idleTime = TimeSpan.FromMilliseconds(Environment.TickCount - last.dwTime);
                // Console.WriteLine("Idle time is: {0}", idleTime);
                if (idleTime > TimeSpan.FromMinutes(10)) {
                    // shutdown here
                }
            }
        }, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
        Console.ReadKey();
        timer.Dispose();            
    }

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

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

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