本文介绍了关闭C#应用程序闲置10分钟后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个C#Windows应用程序,我想添加一个功能,应用程序将闲置10分钟后关闭自动关闭。
的实现代码将受到欢迎。

I am working on a c# windows app and I want to add a feature where the app will shut itself off after 10 minutes of inactivity.any implementation code will be welcome.

推荐答案

您可能需要一些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;
    }
}

这篇关于关闭C#应用程序闲置10分钟后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 07:29