停止活动10分钟后关闭C#应用程序

停止活动10分钟后关闭C#应用程序,c#,C#,我正在开发一个c#windows应用程序,我想添加一个功能,使该应用程序在10分钟不活动后自动关闭。 欢迎使用任何实现代码。您可能需要一些p-invoke,特别是GetLastInputInfo windows函数。它告诉您当前用户上次检测到输入(键盘、鼠标)的时间 internal class Program { private static void Main() { // don't run timer too often, you just need to det

我正在开发一个c#windows应用程序,我想添加一个功能,使该应用程序在10分钟不活动后自动关闭。
欢迎使用任何实现代码。

您可能需要一些p-invoke,特别是GetLastInputInfo windows函数。它告诉您当前用户上次检测到输入(键盘、鼠标)的时间

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;
    }
}

“不活动”指的是在应用程序中什么也不做,或者根本不做(比如用户不在计算机旁)?是的,这就是我的意思。(无需鼠标拖动或按键)什么类型的应用程序:winforms、wpf、console等?windows窗体应用程序