// 定时关机 - 绿色工具箱 // 单文件零依赖(调用系统自带 shutdown.exe),C# 5.0 语法 // 功能:N 分钟后 / 指定时刻关机、重启、休眠、锁屏、注销;倒计时内随时取消 // 边界:不常驻、不写注册表,关掉本程序不影响已下达的系统关机计划(要靠「取消」按钮撤销) // 安全:默认勾选演练模式,只显示命令不真执行;真执行前再确认一次 using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public static class ShutOps { public const int ActShutdown = 0; public const int ActRestart = 1; public const int ActSleep = 2; public const int ActLock = 3; public const int ActLogoff = 4; public static string ActionName(int a) { if (a == ActRestart) return "重启"; if (a == ActSleep) return "休眠"; if (a == ActLock) return "锁屏"; if (a == ActLogoff) return "注销"; return "关机"; } public static string ActionVerb(int a) { if (a == ActRestart) return "重启"; if (a == ActSleep) return "休眠"; if (a == ActLock) return "锁定屏幕"; if (a == ActLogoff) return "注销当前用户"; return "关机"; } // 支持:90(分钟)、90m、1h30m、45s、1:30(时:分)、00:30:00(时:分:秒) public static bool TryParseDuration(string s, out int seconds) { seconds = 0; if (s == null) return false; s = s.Trim().ToLowerInvariant() .Replace("分钟", "m").Replace("小时", "h").Replace("秒钟", "s") .Replace("分", "m").Replace("秒", "s").Replace(" ", "").Replace(" ", ""); if (s.Length == 0) return false; if (s.IndexOf(':') >= 0) { string[] p = s.Split(':'); int[] v = new int[p.Length]; for (int i = 0; i < p.Length; i++) { if (!int.TryParse(p[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out v[i])) return false; if (v[i] < 0) return false; } if (p.Length == 2) { if (v[1] > 59) return false; seconds = v[0] * 3600 + v[1] * 60; } else if (p.Length == 3) { if (v[1] > 59 || v[2] > 59) return false; seconds = v[0] * 3600 + v[1] * 60 + v[2]; } else return false; return seconds > 0; } bool hasUnit = s.IndexOf('h') >= 0 || s.IndexOf('m') >= 0 || s.IndexOf('s') >= 0; if (hasUnit) { int total = 0, cur = 0; bool hasDigit = false; for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c >= '0' && c <= '9') { cur = cur * 10 + (c - '0'); hasDigit = true; continue; } if (!hasDigit) return false; if (c == 'h') total += cur * 3600; else if (c == 'm') total += cur * 60; else if (c == 's') total += cur; else return false; cur = 0; hasDigit = false; } if (hasDigit) total += cur * 60; // 末尾裸数字按分钟算 seconds = total; return seconds > 0; } int n; if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out n)) { if (n <= 0) return false; seconds = n * 60; return true; } return false; } // 指定时刻:过了今天就顺延到明天,避免「填了 09:00 结果立刻关机」 public static bool TryParseClock(string s, DateTime now, out DateTime when) { when = now; if (s == null) return false; s = s.Trim().Replace(":", ":").Replace("点", ":").Replace("时", ":").Replace(" ", ""); if (s.EndsWith("分")) s = s.Substring(0, s.Length - 1); string[] p = s.Split(':'); if (p.Length != 2) return false; int h, m; if (!int.TryParse(p[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out h)) return false; if (!int.TryParse(p[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out m)) return false; if (h < 0 || h > 23 || m < 0 || m > 59) return false; DateTime t = new DateTime(now.Year, now.Month, now.Day, h, m, 0, now.Kind); if (t <= now) t = t.AddDays(1); when = t; return true; } public static int SecondsUntil(DateTime when, DateTime now) { double s = (when - now).TotalSeconds; if (s < 0) return 0; return (int)Math.Ceiling(s); } public static string Human(int seconds) { if (seconds < 0) seconds = 0; int h = seconds / 3600; int m = (seconds % 3600) / 60; int s = seconds % 60; if (h > 0) return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00"); return m.ToString("00") + ":" + s.ToString("00"); } public static string SanitizeNote(string n) { if (n == null) return ""; string t = n.Replace("\"", """).Replace("\r", " ").Replace("\n", " ").Trim(); if (t.Length > 180) t = t.Substring(0, 180); return t; } public static string ProgramFor(int action) { if (action == ActLock || action == ActSleep) return "rundll32.exe"; return "shutdown"; } // 参数与程序名分开传,避免拼成一整行时被引号坑到 public static string BuildArgs(int action, int seconds, string note) { if (action == ActLock) return "user32.dll,LockWorkStation"; if (action == ActSleep) return "powrprof.dll,SetSuspendState 0,1,0"; if (action == ActLogoff) return "/l"; if (seconds < 0) seconds = 0; string flag = action == ActRestart ? "/r" : "/s"; string n = SanitizeNote(note); if (n.Length == 0) return flag + " /t " + seconds; return flag + " /t " + seconds + " /c \"" + n + "\""; } public static string Display(int action, int seconds, string note) { return ProgramFor(action) + " " + BuildArgs(action, seconds, note); } // shutdown /t 的合法上限约 10 年,超过就没意义了 public static int ClampSeconds(int seconds) { if (seconds < 1) return 1; if (seconds > 315359999) return 315359999; return seconds; } // 真执行;返回 null 表示成功,否则返回错误说明 public static string Execute(int action, int seconds, string note, bool drill) { string prog = ProgramFor(action); string args = BuildArgs(action, ClampSeconds(seconds), note); if (drill) return null; try { ProcessStartInfo si = new ProcessStartInfo(); si.FileName = prog; si.Arguments = args; si.CreateNoWindow = true; si.UseShellExecute = false; using (Process p = Process.Start(si)) { p.WaitForExit(4000); if (p.HasExited && p.ExitCode != 0) return "系统拒绝了这条命令(退出码 " + p.ExitCode + "),可能有别的关机任务在排队"; } return null; } catch (Exception ex) { return ex.Message; } } // 取消:只能撤销 shutdown /s /r 的计划,锁屏/休眠立刻发生,撤不了 public static string Cancel(bool drill) { if (drill) return null; try { ProcessStartInfo si = new ProcessStartInfo(); si.FileName = "shutdown"; si.Arguments = "/a"; si.CreateNoWindow = true; si.UseShellExecute = false; using (Process p = Process.Start(si)) { p.WaitForExit(4000); if (p.HasExited && p.ExitCode != 0) return "没有可取消的关机计划(或已经被取消了)"; } return null; } catch (Exception ex) { return ex.Message; } } } public class ShutForm : Form { RadioButton _rbMinutes, _rbClock; NumericUpDown _numMin; TextBox _txtClock, _txtNote; ComboBox _action; CheckBox _drill; Button _start, _cancel; Label _big, _status; Timer _tick; DateTime _deadline = DateTime.MinValue; bool _armed; public ShutForm() { Text = "定时关机 - 绿色工具箱"; ClientSize = new Size(560, 520); MinimumSize = new Size(520, 480); StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9F); Label title = new Label(); title.Text = "到点了自动关机,睡前下东西、渲染任务收尾都省事"; title.AutoSize = false; title.SetBounds(20, 14, 520, 24); title.ForeColor = Color.FromArgb(90, 96, 102); Controls.Add(title); GroupBox box = new GroupBox(); box.Text = "什么时候"; box.SetBounds(20, 46, 520, 118); _rbMinutes = new RadioButton(); _rbMinutes.Text = "倒计时"; _rbMinutes.Checked = true; _rbMinutes.SetBounds(16, 28, 74, 24); _rbMinutes.CheckedChanged += delegate { SyncMode(); }; box.Controls.Add(_rbMinutes); _numMin = new NumericUpDown(); _numMin.Minimum = 1; _numMin.Maximum = 1440; _numMin.Value = 30; _numMin.SetBounds(94, 27, 80, 26); box.Controls.Add(_numMin); Label lbMin = new Label(); lbMin.Text = "分钟后"; lbMin.SetBounds(180, 30, 60, 22); box.Controls.Add(lbMin); _rbClock = new RadioButton(); _rbClock.Text = "指定时刻"; _rbClock.SetBounds(16, 68, 92, 24); box.Controls.Add(_rbClock); _txtClock = new TextBox(); _txtClock.SetBounds(114, 67, 90, 26); _txtClock.Text = "23:00"; box.Controls.Add(_txtClock); Label lbClock = new Label(); lbClock.Text = "(今天已过则算明天)"; lbClock.SetBounds(212, 70, 180, 22); lbClock.ForeColor = Color.FromArgb(130, 136, 142); box.Controls.Add(lbClock); Controls.Add(box); Label lbAct = new Label(); lbAct.Text = "做什么"; lbAct.SetBounds(20, 180, 60, 22); Controls.Add(lbAct); _action = new ComboBox(); _action.DropDownStyle = ComboBoxStyle.DropDownList; _action.Items.AddRange(new object[] { "关机", "重启", "休眠", "锁屏", "注销" }); _action.SelectedIndex = 0; _action.SetBounds(80, 176, 120, 26); Controls.Add(_action); Label lbNote = new Label(); lbNote.Text = "提醒文字"; lbNote.SetBounds(216, 180, 64, 22); Controls.Add(lbNote); _txtNote = new TextBox(); _txtNote.SetBounds(282, 176, 258, 26); _txtNote.Text = "电脑即将关机,请保存工作"; Controls.Add(_txtNote); _drill = new CheckBox(); _drill.Text = "演练模式(只显示要执行的命令,不真关机)"; _drill.Checked = true; _drill.SetBounds(20, 212, 400, 24); Controls.Add(_drill); _start = new Button(); _start.Text = "开始倒计时"; _start.SetBounds(20, 246, 150, 38); _start.BackColor = Color.FromArgb(46, 160, 92); _start.ForeColor = Color.White; _start.FlatStyle = FlatStyle.Flat; _start.FlatAppearance.BorderSize = 0; _start.Click += delegate { Arm(); }; Controls.Add(_start); _cancel = new Button(); _cancel.Text = "取消 / 撤销"; _cancel.SetBounds(182, 246, 120, 38); _cancel.Enabled = false; _cancel.Click += delegate { Disarm(); }; Controls.Add(_cancel); _big = new Label(); _big.Text = "--:--"; _big.Font = new Font("Consolas", 42F, FontStyle.Bold); _big.ForeColor = Color.FromArgb(40, 46, 52); _big.TextAlign = ContentAlignment.MiddleCenter; _big.SetBounds(20, 300, 520, 70); Controls.Add(_big); _status = new Label(); _status.Text = "还没开始"; _status.TextAlign = ContentAlignment.MiddleCenter; _status.ForeColor = Color.FromArgb(120, 126, 132); _status.SetBounds(20, 374, 520, 44); Controls.Add(_status); Label foot = new Label(); foot.Text = "提示:关机计划由系统执行,本窗口关掉也照样生效;反悔请回来点「取消 / 撤销」。"; foot.AutoSize = false; foot.SetBounds(20, 440, 520, 44); foot.ForeColor = Color.FromArgb(150, 156, 162); Controls.Add(foot); _tick = new Timer(); _tick.Interval = 300; _tick.Tick += delegate { UpdateCountdown(); }; _tick.Start(); SyncMode(); } void SyncMode() { _numMin.Enabled = _rbMinutes.Checked; _txtClock.Enabled = !_rbMinutes.Checked; } void Arm() { if (_armed) return; int action = _action.SelectedIndex; int seconds = 0; if (_rbMinutes.Checked) { seconds = (int)_numMin.Value * 60; } else { DateTime when; if (!ShutOps.TryParseClock(_txtClock.Text, DateTime.Now, out when)) { MessageBox.Show("时刻格式看不懂,请按 23:00 这样填(24 小时制)。", "格式不对"); return; } seconds = ShutOps.SecondsUntil(when, DateTime.Now); if (seconds < 1) seconds = 60; } seconds = ShutOps.ClampSeconds(seconds); string verb = ShutOps.ActionVerb(action); string cmd = ShutOps.Display(action, seconds, _txtNote.Text); bool drill = _drill.Checked; string msg = "将在 " + seconds / 60 + " 分 " + seconds % 60 + " 秒后" + verb + "。\r\n\r\n" + (drill ? "【演练模式】只显示命令,不会真的执行。\r\n\r\n" : "【真实执行】到点系统会直接动作,请先保存文件。\r\n\r\n") + "命令:" + cmd; if (MessageBox.Show(msg, "确认一下", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) return; string err = ShutOps.Execute(action, seconds, _txtNote.Text, drill); if (err != null) { MessageBox.Show(err, "没能下达"); return; } if (action == ShutOps.ActLock || action == ShutOps.ActSleep || action == ShutOps.ActLogoff) { // 这三种是立刻生效的,没有倒计时可言 _status.Text = drill ? "演练:" + cmd : ("已执行:" + verb); _big.Text = "--:--"; return; } _armed = true; _deadline = DateTime.Now.AddSeconds(seconds); _start.Enabled = false; _cancel.Enabled = true; _status.Text = drill ? "演练中(系统没被调用):" + cmd : "已下达,系统将在 " + ShutOps.Human(seconds) + " 后" + verb; UpdateCountdown(); } void Disarm() { bool drill = _drill.Checked; if (!drill) { if (MessageBox.Show("撤销这次关机计划?", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) return; } string err = ShutOps.Cancel(drill); _armed = false; _start.Enabled = true; _cancel.Enabled = false; _big.Text = "--:--"; if (err != null) _status.Text = err; else _status.Text = drill ? "演练已结束(系统本来就没被调用)" : "已撤销,电脑不会关机了"; } void UpdateCountdown() { if (!_armed) return; int left = (int)Math.Ceiling((_deadline - DateTime.Now).TotalSeconds); if (left < 0) left = 0; _big.Text = ShutOps.Human(left); if (left <= 0) { _armed = false; _start.Enabled = true; _cancel.Enabled = false; _status.Text = _drill.Checked ? "演练结束(时间到了,什么都没发生)" : "时间到,系统已执行"; } } } public static class ShutSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("定时关机 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); // 注意:本自测绝不调用 shutdown.exe,只验证解析与命令拼接 try { int s; // 纯数字 = 分钟 Check("纯数字按分钟", ShutOps.TryParseDuration("30", out s) && s == 1800, true); Check("0 分钟不合法", ShutOps.TryParseDuration("0", out s), false); Check("负数不合法", ShutOps.TryParseDuration("-5", out s), false); Check("空串不合法", ShutOps.TryParseDuration("", out s), false); Check("乱写不合法", ShutOps.TryParseDuration("abc", out s), false); // 带单位 Check("90m", ShutOps.TryParseDuration("90m", out s) && s == 5400, true); Check("2h", ShutOps.TryParseDuration("2h", out s) && s == 7200, true); Check("1h30m", ShutOps.TryParseDuration("1h30m", out s) && s == 5400, true); Check("45s", ShutOps.TryParseDuration("45s", out s) && s == 45, true); Check("1h2m3s", ShutOps.TryParseDuration("1h2m3s", out s) && s == 3723, true); Check("中文「45分钟」", ShutOps.TryParseDuration("45分钟", out s) && s == 2700, true); Check("中文「1小时30分」", ShutOps.TryParseDuration("1小时30分", out s) && s == 5400, true); // 时间格式 Check("1:30 是 1 小时 30 分", ShutOps.TryParseDuration("1:30", out s) && s == 5400, true); Check("00:00:30 是 30 秒", ShutOps.TryParseDuration("00:00:30", out s) && s == 30, true); Check("分钟位超 59 不合法", ShutOps.TryParseDuration("1:75", out s), false); Check("秒位超 59 不合法", ShutOps.TryParseDuration("1:00:75", out s), false); Check("四段不合法", ShutOps.TryParseDuration("1:2:3:4", out s), false); // 指定时刻 DateTime now = new DateTime(2026, 10, 19, 22, 30, 0); DateTime w; Check("今晚 23:00 就是今天", ShutOps.TryParseClock("23:00", now, out w) && w == new DateTime(2026, 10, 19, 23, 0, 0), true); Check("已过的 09:00 顺延到明天", ShutOps.TryParseClock("09:00", now, out w) && w == new DateTime(2026, 10, 20, 9, 0, 0), true); Check("恰好等于现在也顺延", ShutOps.TryParseClock("22:30", now, out w) && w == new DateTime(2026, 10, 20, 22, 30, 0), true); Check("中文冒号也认", ShutOps.TryParseClock("23:15", now, out w) && w.Hour == 23 && w.Minute == 15, true); Check("「23点」也认", ShutOps.TryParseClock("23点0分", now, out w) && w.Hour == 23 && w.Minute == 0, true); Check("25 点不合法", ShutOps.TryParseClock("25:00", now, out w), false); Check("缺分钟不合法", ShutOps.TryParseClock("23", now, out w), false); Check("剩余秒数", ShutOps.SecondsUntil(new DateTime(2026, 10, 19, 23, 0, 0), now), 1800); Check("已过时间剩余为 0", ShutOps.SecondsUntil(new DateTime(2026, 10, 19, 1, 0, 0), now), 0); // 倒计时文本 Check("一分钟显示", ShutOps.Human(60), "01:00"); Check("一小时显示", ShutOps.Human(3600), "01:00:00"); Check("一小时零一分零一秒", ShutOps.Human(3661), "01:01:01"); Check("负数归零", ShutOps.Human(-10), "00:00"); Check("零点", ShutOps.Human(0), "00:00"); // 命令拼接 Check("关机命令", ShutOps.BuildArgs(ShutOps.ActShutdown, 60, ""), "/s /t 60"); Check("重启命令", ShutOps.BuildArgs(ShutOps.ActRestart, 300, ""), "/r /t 300"); Check("带提醒文字", ShutOps.BuildArgs(ShutOps.ActShutdown, 60, "要关机了"), "/s /t 60 /c \"要关机了\""); Check("注销命令", ShutOps.BuildArgs(ShutOps.ActLogoff, 60, ""), "/l"); Check("锁屏命令", ShutOps.BuildArgs(ShutOps.ActLock, 60, ""), "user32.dll,LockWorkStation"); Check("锁屏用 rundll32", ShutOps.ProgramFor(ShutOps.ActLock), "rundll32.exe"); Check("关机用 shutdown", ShutOps.ProgramFor(ShutOps.ActShutdown), "shutdown"); Check("提醒文字里的引号被换掉", ShutOps.SanitizeNote("说\"关机\"了"), "说"关机"了"); Check("提醒文字换行被压平", ShutOps.SanitizeNote("第一行\r\n第二行"), "第一行 第二行"); Check("提醒文字过长被截断", ShutOps.SanitizeNote(new string('x', 300)).Length, 180); Check("完整命令展示", ShutOps.Display(ShutOps.ActShutdown, 60, "走吧"), "shutdown /s /t 60 /c \"走吧\""); // 秒数收敛 Check("0 秒收敛为 1", ShutOps.ClampSeconds(0), 1); Check("负数收敛为 1", ShutOps.ClampSeconds(-100), 1); Check("超大值被压住", ShutOps.ClampSeconds(int.MaxValue) < int.MaxValue, true); // 动作名 Check("动作名 0", ShutOps.ActionName(0), "关机"); Check("动作名 1", ShutOps.ActionName(1), "重启"); Check("动作名 2", ShutOps.ActionName(2), "休眠"); Check("动作名 3", ShutOps.ActionName(3), "锁屏"); Check("动作名 4", ShutOps.ActionName(4), "注销"); // 演练模式必须真的什么都不做 Check("演练时 Execute 返回成功", ShutOps.Execute(ShutOps.ActShutdown, 60, "测试", true), null); Check("演练时 Cancel 返回成功", ShutOps.Cancel(true), null); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _lines.Add(""); _lines.Add(_fail == 0 ? "结果:共 " + (_pass + _fail) + " 项,全部通过 ✓" : "结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-shutdowntimer.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(ShutSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ShutForm()); } } }