// 桌面时钟 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法 // 功能:无边框悬浮时钟(时间/日期/星期)、12/24 小时制、字号与透明度可调、位置记忆、 // 倒计时(到点提示音)、秒表(计次)、整点报时 // 边界:只读本机时间,不联网对时;设置存 exe 旁 txt,不写注册表 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.IO; using System.Media; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public static class ClockOps { public static string WeekdayCn(DateTime t) { string[] w = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; int i = (int)t.DayOfWeek; if (i < 0 || i > 6) return ""; return w[i]; } // 24 小时制:14:05:09 public static string Format24(DateTime t, bool withSeconds) { return withSeconds ? t.ToString("HH:mm:ss") : t.ToString("HH:mm"); } // 12 小时制:下午 02:05:09 public static string Format12(DateTime t, bool withSeconds) { string ap = t.Hour < 12 ? "上午" : "下午"; int h = t.Hour % 12; if (h == 0) h = 12; string hm = h.ToString("00") + ":" + t.Minute.ToString("00"); if (withSeconds) hm += ":" + t.Second.ToString("00"); return ap + " " + hm; } public static string DateText(DateTime t) { return t.ToString("yyyy 年 M 月 d 日") + " " + WeekdayCn(t); } // 倒计时输入:纯数字=分钟;1:30=1 分 30 秒;1:02:03=时分秒;支持 1h30m / 90s public static bool TryParseCountdown(string s, out int seconds) { seconds = 0; if (s == null) return false; s = s.Trim().ToLowerInvariant() .Replace("分钟", "m").Replace("小时", "h").Replace("秒钟", "s").Replace("秒", "s") .Replace("分", "m").Replace(" ", "").Replace(" ", ""); if (s.Length == 0) return false; if (s.IndexOf(':') >= 0) { string[] p = s.Split(':'); if (p.Length < 2 || p.Length > 3) return false; 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] * 60 + v[1]; } else { if (v[1] > 59 || v[2] > 59) return false; seconds = v[0] * 3600 + v[1] * 60 + v[2]; } return seconds > 0 && seconds <= 99 * 3600; } // 复合单位:1h30m、90s、25m int total = 0, num = 0; bool hasUnit = false, hasDigit = false; for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c >= '0' && c <= '9') { num = num * 10 + (c - '0'); hasDigit = true; if (num > 100000) return false; } else if (c == 'h' || c == 'm' || c == 's') { if (!hasDigit) return false; hasUnit = true; if (c == 'h') total += num * 3600; else if (c == 'm') total += num * 60; else total += num; num = 0; hasDigit = false; } else return false; } if (hasDigit) total += num * 60; // 结尾裸数字按分钟 if (!hasUnit && !hasDigit) return false; seconds = total; return seconds > 0 && seconds <= 99 * 3600; } public static string FormatHms(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 FormatStopwatch(int centis) { if (centis < 0) centis = 0; int m = centis / 6000; int s = (centis % 6000) / 100; int c = centis % 100; return m.ToString("00") + ":" + s.ToString("00") + "." + c.ToString("00"); } public static bool TryParsePosition(string s, out Point p) { p = new Point(0, 0); if (s == null) return false; string[] parts = s.Trim().Replace(",", ",").Replace(" ", "").Split(','); if (parts.Length != 2) return false; int x, y; if (!int.TryParse(parts[0], out x) || !int.TryParse(parts[1], out y)) return false; if (x < -20000 || x > 20000 || y < -20000 || y > 20000) return false; p = new Point(x, y); return true; } // 整点报时判定:分秒都为 0,且这一小时内没报过 public static bool ShouldChime(DateTime now, DateTime lastChime) { if (now.Minute != 0 || now.Second > 2) return false; if (lastChime.Year == now.Year && lastChime.Month == now.Month && lastChime.Day == now.Day && lastChime.Hour == now.Hour) return false; return true; } } public class ClockForm : Form { enum Mode { Clock, Countdown, Stopwatch } Mode _mode = Mode.Clock; Label _time, _sub; Timer _tick; ContextMenuStrip _menu; ToolStripMenuItem m12, mSec, mTop, mChime; bool _drag; Point _dragOffset; int _fontSize = 34; int _opacity = 100; bool _use24 = true; bool _showSeconds = true; bool _topMost = true; bool _chime = false; bool _locked = false; DateTime _lastChime = DateTime.MinValue; int _countdownLeft = 0; bool _countdownRunning = false; DateTime _countdownEnd = DateTime.MinValue; int _swBaseCentis = 0; DateTime _swStart = DateTime.MinValue; bool _swRunning = false; List _laps = new List(); int SwCentis { get { if (!_swRunning) return _swBaseCentis; double add = (DateTime.Now - _swStart).TotalMilliseconds / 10.0; return _swBaseCentis + (int)add; } } public ClockForm() { FormBorderStyle = FormBorderStyle.None; StartPosition = FormStartPosition.Manual; BackColor = Color.FromArgb(24, 26, 30); ShowInTaskbar = true; Text = "桌面时钟"; ClientSize = new Size(400, 130); DoubleBuffered = true; _time = new Label(); _time.AutoSize = false; _time.TextAlign = ContentAlignment.MiddleCenter; _time.ForeColor = Color.FromArgb(120, 235, 180); _time.BackColor = Color.Transparent; _time.SetBounds(0, 6, 400, 60); _time.Font = new Font("Consolas", _fontSize, FontStyle.Bold); _sub = new Label(); _sub.AutoSize = false; _sub.TextAlign = ContentAlignment.MiddleCenter; _sub.ForeColor = Color.FromArgb(190, 195, 205); _sub.BackColor = Color.Transparent; _sub.SetBounds(0, 68, 400, 26); _sub.Font = new Font("Microsoft YaHei UI", 9.5f); Controls.Add(_sub); Controls.Add(_time); Controls.SetChildIndex(_time, 0); BuildMenu(); _tick = new Timer(); _tick.Interval = 50; _tick.Tick += delegate { OnTick(); }; MouseDown += OnMouseDown; MouseMove += OnMouseMove; MouseUp += delegate { _drag = false; }; _time.MouseDown += OnMouseDown; _time.MouseMove += OnMouseMove; _time.MouseUp += delegate { _drag = false; }; _sub.MouseDown += OnMouseDown; _sub.MouseMove += OnMouseMove; _sub.MouseUp += delegate { _drag = false; }; MouseDoubleClick += delegate { _locked = !_locked; UpdateHint(); }; Load += delegate { LoadSettings(); m12.Checked = !_use24; mSec.Checked = _showSeconds; mTop.Checked = _topMost; mChime.Checked = _chime; TopMost = _topMost; Opacity = _opacity / 100.0; ApplyModeUI(); UpdateClock(); _tick.Start(); }; FormClosing += delegate { SaveSettings(); }; } string ConfigPath { get { string dir = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "时钟设置"); try { Directory.CreateDirectory(dir); } catch { dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GreenToolbox/时钟设置"); Directory.CreateDirectory(dir); } return Path.Combine(dir, "clock.ini"); } } void BuildMenu() { _menu = new ContextMenuStrip(); _menu.Font = new Font("Microsoft YaHei UI", 9.5f); ToolStripMenuItem mClock = new ToolStripMenuItem("时钟模式"); mClock.Click += delegate { _mode = Mode.Clock; _countdownRunning = false; _swRunning = false; ApplyModeUI(); }; _menu.Items.Add(mClock); ToolStripMenuItem mCount = new ToolStripMenuItem("倒计时…"); mCount.Click += delegate { AskCountdown(); }; _menu.Items.Add(mCount); ToolStripMenuItem mSw = new ToolStripMenuItem("秒表"); mSw.Click += delegate { _mode = Mode.Stopwatch; _countdownRunning = false; ApplyModeUI(); }; _menu.Items.Add(mSw); _menu.Items.Add(new ToolStripSeparator()); m12 = new ToolStripMenuItem("12 小时制"); m12.CheckOnClick = true; m12.Checked = !_use24; m12.Click += delegate { _use24 = !m12.Checked; SaveSettings(); UpdateClock(); }; _menu.Items.Add(m12); mSec = new ToolStripMenuItem("显示秒"); mSec.CheckOnClick = true; mSec.Checked = true; mSec.Click += delegate { _showSeconds = mSec.Checked; SaveSettings(); UpdateClock(); }; _menu.Items.Add(mSec); mTop = new ToolStripMenuItem("总在最前"); mTop.CheckOnClick = true; mTop.Checked = _topMost; mTop.Click += delegate { _topMost = mTop.Checked; TopMost = _topMost; SaveSettings(); }; _menu.Items.Add(mTop); mChime = new ToolStripMenuItem("整点报时"); mChime.CheckOnClick = true; mChime.Click += delegate { _chime = mChime.Checked; SaveSettings(); }; _menu.Items.Add(mChime); ToolStripMenuItem mBig = new ToolStripMenuItem("字号加大"); mBig.Click += delegate { SetFontSize(_fontSize + 4); }; _menu.Items.Add(mBig); ToolStripMenuItem mSmall = new ToolStripMenuItem("字号减小"); mSmall.Click += delegate { SetFontSize(_fontSize - 4); }; _menu.Items.Add(mSmall); ToolStripMenuItem mMore = new ToolStripMenuItem("更不透明"); mMore.Click += delegate { SetOpacity(_opacity + 10); }; _menu.Items.Add(mMore); ToolStripMenuItem mLess = new ToolStripMenuItem("更透明"); mLess.Click += delegate { SetOpacity(_opacity - 10); }; _menu.Items.Add(mLess); _menu.Items.Add(new ToolStripSeparator()); ToolStripMenuItem mResetSw = new ToolStripMenuItem("秒表:开始 / 暂停"); mResetSw.Click += delegate { if (_mode != Mode.Stopwatch) { _mode = Mode.Stopwatch; ApplyModeUI(); } if (_swRunning) { _swBaseCentis = SwCentis; _swRunning = false; } else { _swStart = DateTime.Now; _swRunning = true; } }; _menu.Items.Add(mResetSw); ToolStripMenuItem mLap = new ToolStripMenuItem("秒表:计次"); mLap.Click += delegate { if (SwCentis > 0) { _laps.Add(ClockOps.FormatStopwatch(SwCentis)); _swBaseCentis = 0; _swStart = DateTime.Now; UpdateStopwatch(); } }; _menu.Items.Add(mLap); ToolStripMenuItem mClearSw = new ToolStripMenuItem("秒表:归零"); mClearSw.Click += delegate { _swBaseCentis = 0; _swRunning = false; _laps.Clear(); UpdateStopwatch(); }; _menu.Items.Add(mClearSw); _menu.Items.Add(new ToolStripSeparator()); ToolStripMenuItem mExit = new ToolStripMenuItem("退出"); mExit.Click += delegate { Close(); }; _menu.Items.Add(mExit); ContextMenuStrip = _menu; _time.ContextMenuStrip = _menu; _sub.ContextMenuStrip = _menu; } void SetFontSize(int v) { if (v < 14) v = 14; if (v > 96) v = 96; _fontSize = v; _time.Font = new Font("Consolas", _fontSize, FontStyle.Bold); int h = (int)Math.Ceiling(_fontSize * 1.7); ClientSize = new Size(ClientSize.Width, h + 42); _time.SetBounds(0, 4, ClientSize.Width, h); _sub.SetBounds(0, h + 6, ClientSize.Width, 26); SaveSettings(); } void SetOpacity(int v) { if (v < 30) v = 30; if (v > 100) v = 100; _opacity = v; Opacity = v / 100.0; SaveSettings(); } void AskCountdown() { using (Form dlg = new Form()) { dlg.Text = "倒计时"; dlg.FormBorderStyle = FormBorderStyle.FixedDialog; dlg.StartPosition = FormStartPosition.CenterParent; dlg.MaximizeBox = false; dlg.MinimizeBox = false; dlg.ClientSize = new Size(320, 130); dlg.Font = new Font("Microsoft YaHei UI", 9.5f); Label l = new Label(); l.Text = "多久后提醒?(如 25、1:30、1h30m)"; l.SetBounds(14, 14, 290, 40); TextBox tb = new TextBox(); tb.SetBounds(14, 54, 290, 26); tb.Text = "25"; Button ok = new Button(); ok.Text = "开始"; ok.SetBounds(146, 90, 74, 28); ok.DialogResult = DialogResult.OK; Button cancel = new Button(); cancel.Text = "取消"; cancel.SetBounds(230, 90, 74, 28); cancel.DialogResult = DialogResult.Cancel; dlg.Controls.Add(l); dlg.Controls.Add(tb); dlg.Controls.Add(ok); dlg.Controls.Add(cancel); dlg.AcceptButton = ok; dlg.CancelButton = cancel; if (dlg.ShowDialog(this) != DialogResult.OK) return; int sec; if (!ClockOps.TryParseCountdown(tb.Text, out sec)) { MessageBox.Show("时间格式不对,请填 25(分钟)、1:30、1h30m 这样的写法。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } _countdownLeft = sec; _countdownEnd = DateTime.Now.AddSeconds(sec); _countdownRunning = true; _mode = Mode.Countdown; ApplyModeUI(); } } void ApplyModeUI() { _time.Font = new Font("Consolas", _fontSize, FontStyle.Bold); if (_mode == Mode.Clock) UpdateClock(); else if (_mode == Mode.Countdown) UpdateCountdown(); else UpdateStopwatch(); } void UpdateHint() { if (_mode != Mode.Clock) return; string tail = _locked ? "已锁定,双击解锁" : "拖动 · 双击锁定 · 右键菜单"; _sub.Text = ClockOps.DateText(DateTime.Now) + " " + tail; } void OnTick() { if (_mode == Mode.Clock) { UpdateClock(); if (_chime) { DateTime now = DateTime.Now; if (ClockOps.ShouldChime(now, _lastChime)) { _lastChime = now; try { SystemSounds.Asterisk.Play(); } catch { } } } } else if (_mode == Mode.Countdown) { if (_countdownRunning) { double remain = (_countdownEnd - DateTime.Now).TotalSeconds; _countdownLeft = remain > 0 ? (int)Math.Ceiling(remain) : 0; if (_countdownLeft <= 0) { _countdownLeft = 0; OnCountdownEnd(); } } UpdateCountdown(); } else { UpdateStopwatch(); } } void OnCountdownEnd() { _countdownRunning = false; for (int i = 0; i < 3; i++) { try { SystemSounds.Exclamation.Play(); } catch { } System.Threading.Thread.Sleep(220); } try { NotifyIcon ni = new NotifyIcon(); ni.Icon = SystemIcons.Information; ni.Visible = true; ni.ShowBalloonTip(4000, "倒计时结束", "设置的时间到了。", ToolTipIcon.Info); Timer t = new Timer(); t.Interval = 4500; t.Tick += delegate { t.Stop(); ni.Visible = false; ni.Dispose(); }; t.Start(); } catch { } } void UpdateClock() { if (_mode != Mode.Clock) return; DateTime now = DateTime.Now; _time.Text = _use24 ? ClockOps.Format24(now, _showSeconds) : ClockOps.Format12(now, _showSeconds); string tail = _locked ? "已锁定,双击解锁" : "拖动 · 双击锁定 · 右键菜单"; _sub.Text = ClockOps.DateText(now) + " " + tail; } void UpdateCountdown() { _time.Text = ClockOps.FormatHms(_countdownLeft); string st = _countdownRunning ? "倒计时中" : (_countdownLeft == 0 ? "时间到" : "已暂停"); _sub.Text = st + " 右键菜单可重新设置"; _time.ForeColor = _countdownLeft == 0 ? Color.FromArgb(255, 140, 120) : Color.FromArgb(120, 235, 180); } void UpdateStopwatch() { _time.Text = ClockOps.FormatStopwatch(SwCentis); string st = _swRunning ? "计时中" : "已暂停"; string lap = _laps.Count > 0 ? " 最新计次 " + _laps[_laps.Count - 1] : ""; _sub.Text = st + " 右键菜单:开始/计次/归零" + lap; _time.ForeColor = Color.FromArgb(140, 200, 255); } void OnMouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && !_locked) { _drag = true; _dragOffset = new Point(e.X + ((Control)sender).Left, e.Y + ((Control)sender).Top); } } void OnMouseMove(object sender, MouseEventArgs e) { if (!_drag) return; Point screen = PointToScreen(new Point(e.X + ((Control)sender).Left, e.Y + ((Control)sender).Top)); Location = new Point(screen.X - _dragOffset.X, screen.Y - _dragOffset.Y); } void LoadSettings() { Point pos = new Point(-1, -1); try { if (File.Exists(ConfigPath)) { foreach (string line in File.ReadAllLines(ConfigPath, Encoding.UTF8)) { int i = line.IndexOf('='); if (i < 0) continue; string k = line.Substring(0, i).Trim(); string v = line.Substring(i + 1).Trim(); int n; if (k == "x" || k == "y") { } if (k == "pos") ClockOps.TryParsePosition(v, out pos); else if (k == "font" && int.TryParse(v, out n)) _fontSize = Math.Max(14, Math.Min(96, n)); else if (k == "opacity" && int.TryParse(v, out n)) _opacity = Math.Max(30, Math.Min(100, n)); else if (k == "use24") _use24 = v != "0"; else if (k == "seconds") _showSeconds = v != "0"; else if (k == "topmost") _topMost = v != "0"; else if (k == "chime") _chime = v != "0"; } } } catch { } SetFontSize(_fontSize); if (pos.X > -10000 && pos.Y > -10000 && pos != new Point(-1, -1)) Location = pos; else { Rectangle wa = Screen.PrimaryScreen.WorkingArea; Location = new Point(wa.Right - Width - 40, wa.Top + 40); } } void SaveSettings() { try { StringBuilder sb = new StringBuilder(); sb.AppendLine("pos=" + Location.X + "," + Location.Y); sb.AppendLine("font=" + _fontSize); sb.AppendLine("opacity=" + _opacity); sb.AppendLine("use24=" + (_use24 ? "1" : "0")); sb.AppendLine("seconds=" + (_showSeconds ? "1" : "0")); sb.AppendLine("topmost=" + (_topMost ? "1" : "0")); sb.AppendLine("chime=" + (_chime ? "1" : "0")); File.WriteAllText(ConfigPath, sb.ToString(), new UTF8Encoding(false)); } catch { } } } public static class ClockSelfTest { 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")); try { DateTime t = new DateTime(2026, 10, 19, 14, 5, 9); Check("24 小时制带秒", ClockOps.Format24(t, true), "14:05:09"); Check("24 小时制不带秒", ClockOps.Format24(t, false), "14:05"); Check("12 小时制下午", ClockOps.Format12(t, true), "下午 02:05:09"); Check("12 小时制上午", ClockOps.Format12(new DateTime(2026, 1, 1, 9, 3, 0), false), "上午 09:03"); Check("午夜 0 点显示 12", ClockOps.Format12(new DateTime(2026, 1, 1, 0, 30, 0), false), "上午 12:30"); Check("中午 12 点显示 12", ClockOps.Format12(new DateTime(2026, 1, 1, 12, 30, 0), false), "下午 12:30"); Check("11 点仍是上午", ClockOps.Format12(new DateTime(2026, 1, 1, 11, 59, 0), false), "上午 11:59"); Check("星期:2026-10-19 是星期一", ClockOps.WeekdayCn(new DateTime(2026, 10, 19)), "星期一"); Check("星期:2026-10-18 是星期日", ClockOps.WeekdayCn(new DateTime(2026, 10, 18)), "星期日"); Check("日期文本", ClockOps.DateText(new DateTime(2026, 10, 19)), "2026 年 10 月 19 日 星期一"); int s; Check("纯数字按分钟", ClockOps.TryParseCountdown("25", out s) && s == 1500, true); Check("1:30 是 1 分 30 秒", ClockOps.TryParseCountdown("1:30", out s) && s == 90, true); Check("1:02:03", ClockOps.TryParseCountdown("1:02:03", out s) && s == 3723, true); Check("1h30m", ClockOps.TryParseCountdown("1h30m", out s) && s == 5400, true); Check("90s", ClockOps.TryParseCountdown("90s", out s) && s == 90, true); Check("中文 25分钟", ClockOps.TryParseCountdown("25分钟", out s) && s == 1500, true); Check("0 不合法", ClockOps.TryParseCountdown("0", out s), false); Check("0:00 不合法", ClockOps.TryParseCountdown("0:00", out s), false); Check("秒位超 59 不合法", ClockOps.TryParseCountdown("1:75", out s), false); Check("乱写不合法", ClockOps.TryParseCountdown("abc", out s), false); Check("超 99 小时不合法", ClockOps.TryParseCountdown("100h", out s), false); Check("格式化 1 小时 2 分 5 秒", ClockOps.FormatHms(3725), "01:02:05"); Check("格式化 45 秒", ClockOps.FormatHms(45), "00:45"); Check("格式化负数按 0", ClockOps.FormatHms(-5), "00:00"); Check("秒表格式化", ClockOps.FormatStopwatch(7542), "01:15.42"); Check("秒表零", ClockOps.FormatStopwatch(0), "00:00.00"); Point p; Check("位置解析", ClockOps.TryParsePosition("120,80", out p) && p.X == 120 && p.Y == 80, true); Check("位置中文逗号", ClockOps.TryParsePosition("120,80", out p) && p.Y == 80, true); Check("位置格式错", ClockOps.TryParsePosition("120", out p), false); Check("位置越界", ClockOps.TryParsePosition("99999,1", out p), false); DateTime now = new DateTime(2026, 10, 19, 15, 0, 0); Check("整点该报时", ClockOps.ShouldChime(now, DateTime.MinValue), true); Check("同一小时不重复报", ClockOps.ShouldChime(now, new DateTime(2026, 10, 19, 15, 0, 1)), false); Check("半点不报时", ClockOps.ShouldChime(new DateTime(2026, 10, 19, 15, 30, 0), DateTime.MinValue), false); Check("上一小时不影响本小时", ClockOps.ShouldChime(now, new DateTime(2026, 10, 19, 14, 0, 0)), true); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 异常:" + ex.Message); } _lines.Add("通过 " + _pass + " / " + (_pass + _fail)); string all = string.Join("\r\n", _lines.ToArray()) + "\r\n"; Console.WriteLine(all); try { string root = string.IsNullOrEmpty(dir) ? Directory.GetCurrentDirectory() : dir; Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "selftest-deskclock.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(ClockSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ClockForm()); } } }