在C#中实现程序长时间未用自动关闭,可通过监测用户空闲时间来实现。以下是完整解决方案:
实现原理
- 使用Windows API获取系统最后输入时间
- 创建定时器定期检测空闲时间
- 当空闲超过阈值时触发关闭
代码实现
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;
}
}
关键说明
-
空闲检测原理:
- 使用
GetLastInputInfoAPI获取最后输入时间戳 - 计算当前系统运行时间与最后输入时间的差值
- 公式:空闲时间=当前Tick−最后输入Tick60000 \text{空闲时间} = \frac{\text{当前Tick} - \text{最后输入Tick}}{60000} 空闲时间=60000当前Tick−最后输入Tick
- 使用
-
定时器设置:
- 每分钟检查一次(
60000毫秒间隔) - 可通过修改
IDLE_MINUTES调整空闲阈值
- 每分钟检查一次(
-
系统托盘图标:
- 使用
NotifyIcon实现后台运行 - 右键托盘图标可添加退出菜单
- 使用
扩展建议
-
添加预警提示:
if (idleTime == IDLE_MINUTES - 1) { MessageBox.Show("程序将在1分钟后自动关闭"); } -
保存状态:
在退出前自动保存应用程序状态 -
跨平台方案:
如需支持Linux/macOS,需改用System.Diagnostics.Stopwatch计时
注意:此实现需要
System.Windows.Forms引用,适用于Windows平台。控制台程序需添加[STAThread]特性到Main方法。
327

被折叠的 条评论
为什么被折叠?



