C#中实现程序长时间未用自动关闭

在C#中实现程序长时间未用自动关闭,可通过监测用户空闲时间来实现。以下是完整解决方案:

实现原理

  1. 使用Windows API获取系统最后输入时间
  2. 创建定时器定期检测空闲时间
  3. 当空闲超过阈值时触发关闭

代码实现

using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

class Program
{
    // 导入Windows API
    [DllImport("user32.dll")]
    static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

    [StructLayout(LayoutKind.Sequential)]
    struct LASTINPUTINFO
    {
        public uint cbSize;
        public uint dwTime;
    }

    static Timer idleTimer;
    const int IDLE_MINUTES = 30;  // 30分钟无操作自动关闭

    static void Main()
    {
        // 创建系统托盘图标(可选)
        NotifyIcon trayIcon = new NotifyIcon();
        trayIcon.Icon = SystemIcons.Application;
        trayIcon.Visible = true;
        
        // 初始化计时器
        idleTimer = new Timer(CheckIdleTime, null, 0, 60000);  // 每分钟检查一次
        
        // 保持程序运行
        Application.Run();
    }

    static void CheckIdleTime(object state)
    {
        uint idleTime = GetIdleTimeInMinutes();
        if (idleTime >= IDLE_MINUTES)
        {
            // 关闭程序
            Environment.Exit(0);
        }
    }

    static uint GetIdleTimeInMinutes()
    {
        LASTINPUTINFO lastInput = new LASTINPUTINFO();
        lastInput.cbSize = (uint)Marshal.SizeOf(lastInput);
        GetLastInputInfo(ref lastInput);

        uint lastInputTime = lastInput.dwTime;
        uint currentTick = (uint)Environment.TickCount;
        
        // 计算空闲时间(分钟)
        return (currentTick - lastInputTime) / 60000; 
    }
}

关键说明

  1. 空闲检测原理

    • 使用GetLastInputInfo API获取最后输入时间戳
    • 计算当前系统运行时间与最后输入时间的差值
    • 公式:空闲时间=当前Tick−最后输入Tick60000 \text{空闲时间} = \frac{\text{当前Tick} - \text{最后输入Tick}}{60000} 空闲时间=60000当前Tick最后输入Tick
  2. 定时器设置

    • 每分钟检查一次(60000毫秒间隔)
    • 可通过修改IDLE_MINUTES调整空闲阈值
  3. 系统托盘图标

    • 使用NotifyIcon实现后台运行
    • 右键托盘图标可添加退出菜单

扩展建议

  1. 添加预警提示

    if (idleTime == IDLE_MINUTES - 1) 
    {
        MessageBox.Show("程序将在1分钟后自动关闭");
    }
    
  2. 保存状态
    在退出前自动保存应用程序状态

  3. 跨平台方案
    如需支持Linux/macOS,需改用System.Diagnostics.Stopwatch计时

注意:此实现需要System.Windows.Forms引用,适用于Windows平台。控制台程序需添加[STAThread]特性到Main方法。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值