// 桌面日历 + 每日备注 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法 // 功能:月历总览、点日期写当天备注、有备注的日子带小圆点、一键导出当月备注 // 边界:不做农历/节气/节假日调休(那需要每年更新的数据表,本工具只认公历) // 存储:备注目录下一天一个 txt(2026-10-19.txt),删掉备注文件就是删掉那天 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public static class CalOps { public static bool IsLeap(int y) { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; } public static int DaysInMonth(int y, int m) { if (m < 1 || m > 12) return 0; if (m == 2) return IsLeap(y) ? 29 : 28; if (m == 4 || m == 6 || m == 9 || m == 11) return 30; return 31; } public static DateTime FirstOfMonth(int y, int m) { return new DateTime(y, m, 1); } // 周一当第一列:周日要排到最后,所以 (dow + 6) % 7 public static int MondayIndex(DayOfWeek d) { return ((int)d + 6) % 7; } // 固定 42 格(6 行),前后用上/下月的日子补满,格子位置不跳动 public static List BuildGrid(int y, int m) { List r = new List(42); DateTime first = FirstOfMonth(y, m); int off = MondayIndex(first.DayOfWeek); DateTime start = first.AddDays(-off); for (int i = 0; i < 42; i++) r.Add(start.AddDays(i)); return r; } public static string MonthTitle(int y, int m) { return y + " 年 " + m + " 月"; } public static void Shift(ref int y, ref int m, int delta) { int total = y * 12 + (m - 1) + delta; int ny = total / 12; int nm = total % 12; if (nm < 0) { nm += 12; ny -= 1; } y = ny; m = nm + 1; } public static string WeekName(DayOfWeek d) { string[] n = new string[] { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; return n[(int)d]; } public static string NotePath(string dir, DateTime d) { return Path.Combine(dir, d.ToString("yyyy-MM-dd") + ".txt"); } public static string LoadNote(string dir, DateTime d) { string p = NotePath(dir, d); if (!File.Exists(p)) return ""; try { return File.ReadAllText(p, Encoding.UTF8); } catch { return ""; } } // 写成空备注 = 删除这天的记录,不留空文件 public static bool SaveNote(string dir, DateTime d, string text) { Directory.CreateDirectory(dir); string p = NotePath(dir, d); string t = text == null ? "" : text.Trim(); if (t.Length == 0) { if (File.Exists(p)) { File.Delete(p); return true; } return false; } File.WriteAllText(p, text, new UTF8Encoding(false)); return true; } // 当月有备注的日子(用于画小圆点) public static HashSet NoteDays(string dir, int y, int m) { HashSet set = new HashSet(); if (!Directory.Exists(dir)) return set; string prefix = string.Format("{0:0000}-{1:00}-", y, m); string[] files = Directory.GetFiles(dir, "*.txt"); for (int i = 0; i < files.Length; i++) { string name = Path.GetFileNameWithoutExtension(files[i]); if (!name.StartsWith(prefix, StringComparison.Ordinal)) continue; int day; if (name.Length != 10) continue; if (!int.TryParse(name.Substring(8, 2), out day)) continue; if (day < 1 || day > DaysInMonth(y, m)) continue; set.Add(day); } return set; } // 导出当月:只列有备注的日子,按日期升序 public static string ExportMonth(string dir, int y, int m) { StringBuilder sb = new StringBuilder(); sb.Append(MonthTitle(y, m)).Append(" 备注\r\n"); sb.Append("============================\r\n\r\n"); int days = DaysInMonth(y, m); int n = 0; for (int d = 1; d <= days; d++) { DateTime dt = new DateTime(y, m, d); string note = LoadNote(dir, dt); if (note.Trim().Length == 0) continue; sb.Append(dt.ToString("MM-dd")).Append(" ").Append(WeekName(dt.DayOfWeek)).Append("\r\n"); sb.Append(note.Trim()).Append("\r\n\r\n"); n++; } if (n == 0) sb.Append("(这个月还没写备注)\r\n"); return sb.ToString(); } public static int CountMonth(string dir, int y, int m) { return NoteDays(dir, y, m).Count; } } public class CalGridPanel : Panel { public List Grid = new List(); public int Year = DateTime.Today.Year; public int Month = DateTime.Today.Month; public DateTime Selected = DateTime.Today; public HashSet Marks = new HashSet(); public event EventHandler DayClicked; public CalGridPanel() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); BackColor = Color.White; } const int HeadH = 30; int CellW { get { return Math.Max(1, ClientSize.Width / 7); } } int CellH { get { return Math.Max(1, (ClientSize.Height - HeadH) / 6); } } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; g.Clear(Color.White); int cw = CellW, ch = CellH; string[] heads = new string[] { "一", "二", "三", "四", "五", "六", "日" }; using (Font hf = new Font("Microsoft YaHei UI", 9F, FontStyle.Bold)) using (Pen line = new Pen(Color.FromArgb(232, 236, 240))) { for (int i = 0; i < 7; i++) { Rectangle hr = new Rectangle(i * cw, 0, cw, HeadH); TextRenderer.DrawText(g, heads[i], hf, hr, i >= 5 ? Color.FromArgb(214, 92, 92) : Color.FromArgb(95, 105, 115), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); } g.DrawLine(line, 0, HeadH - 1, ClientSize.Width, HeadH - 1); DateTime today = DateTime.Today; for (int idx = 0; idx < 42 && idx < Grid.Count; idx++) { DateTime d = Grid[idx]; int col = idx % 7, row = idx / 7; Rectangle r = new Rectangle(col * cw, HeadH + row * ch, cw, ch); bool other = d.Month != Month; bool isSel = d.Date == Selected.Date; bool isToday = d.Date == today; if (isSel) { using (SolidBrush b = new SolidBrush(Color.FromArgb(235, 246, 238))) g.FillRectangle(b, r); using (Pen p = new Pen(Color.FromArgb(46, 160, 92), 2)) g.DrawRectangle(p, r.X + 1, r.Y + 1, r.Width - 3, r.Height - 3); } else if (isToday) { using (SolidBrush b = new SolidBrush(Color.FromArgb(255, 246, 240))) g.FillRectangle(b, r); } Color numColor; if (isSel) numColor = Color.FromArgb(20, 120, 60); else if (other) numColor = Color.FromArgb(190, 195, 200); else if (col >= 5) numColor = Color.FromArgb(210, 90, 90); else numColor = Color.FromArgb(45, 50, 55); using (Font df = new Font("Microsoft YaHei UI", isToday ? 13F : 12F, isToday ? FontStyle.Bold : FontStyle.Regular)) { TextRenderer.DrawText(g, d.Day.ToString(), df, new Rectangle(r.X, r.Y + 6, r.Width, 24), numColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.Top); } // 有备注:右下角一个小绿点 if (!other && Marks.Contains(d.Day)) { using (SolidBrush b = new SolidBrush(Color.FromArgb(46, 160, 92))) g.FillEllipse(b, r.Right - 14, r.Bottom - 12, 6, 6); } } // 网格线 using (Pen p = new Pen(Color.FromArgb(240, 243, 246))) { for (int i = 1; i < 7; i++) g.DrawLine(p, i * cw, HeadH, i * cw, HeadH + 6 * ch); for (int i = 1; i < 6; i++) g.DrawLine(p, 0, HeadH + i * ch, ClientSize.Width, HeadH + i * ch); } } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (e.Button != MouseButtons.Left) return; int row = (e.Y - HeadH) / CellH; int col = e.X / CellW; if (row < 0 || row > 5 || col < 0 || col > 6) return; int idx = row * 7 + col; if (idx < 0 || idx >= Grid.Count) return; Selected = Grid[idx]; Invalidate(); if (DayClicked != null) DayClicked(this, EventArgs.Empty); } } public class DeskCalForm : Form { string _dir; int _y, _m; CalGridPanel _grid; RichTextBox _note; Label _noteTitle; Label _monthStat; Timer _saveTimer; bool _loading; public DeskCalForm() { Text = "桌面日历 - 绿色工具箱"; ClientSize = new Size(940, 600); MinimumSize = new Size(760, 500); StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9F); BackColor = Color.White; _dir = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "日历备注"); DateTime now = DateTime.Today; _y = now.Year; _m = now.Month; Panel bar = new Panel(); bar.Dock = DockStyle.Top; bar.Height = 52; bar.BackColor = Color.FromArgb(250, 251, 252); Button prev = new Button(); prev.Text = "‹"; prev.Font = new Font("Microsoft YaHei UI", 13F); prev.SetBounds(14, 10, 40, 32); prev.Click += delegate { CalOps.Shift(ref _y, ref _m, -1); GoMonth(); }; bar.Controls.Add(prev); Button next = new Button(); next.Text = "›"; next.Font = new Font("Microsoft YaHei UI", 13F); next.SetBounds(58, 10, 40, 32); next.Click += delegate { CalOps.Shift(ref _y, ref _m, 1); GoMonth(); }; bar.Controls.Add(next); Button today = new Button(); today.Text = "回到今天"; today.SetBounds(108, 10, 92, 32); today.Click += delegate { DateTime t = DateTime.Today; _y = t.Year; _m = t.Month; _grid.Selected = t; GoMonth(); }; bar.Controls.Add(today); Label title = new Label(); title.Font = new Font("Microsoft YaHei UI", 14F, FontStyle.Bold); title.ForeColor = Color.FromArgb(40, 46, 52); title.AutoSize = false; title.SetBounds(216, 12, 220, 30); title.Name = "title"; title.Text = CalOps.MonthTitle(_y, _m); bar.Controls.Add(title); _monthStat = new Label(); _monthStat.AutoSize = false; _monthStat.SetBounds(440, 18, 200, 22); _monthStat.ForeColor = Color.FromArgb(130, 138, 145); bar.Controls.Add(_monthStat); Button export = new Button(); export.Text = "导出本月备注"; export.SetBounds(650, 10, 118, 32); export.Click += delegate { ExportMonth(); }; bar.Controls.Add(export); Label tip = new Label(); tip.Text = "备注只存本机"; tip.AutoSize = false; tip.SetBounds(776, 18, 120, 22); tip.ForeColor = Color.FromArgb(150, 155, 160); bar.Controls.Add(tip); Controls.Add(bar); Panel right = new Panel(); right.Dock = DockStyle.Right; right.Width = 330; right.Padding = new Padding(14, 10, 14, 12); right.BackColor = Color.FromArgb(250, 251, 252); _noteTitle = new Label(); _noteTitle.Dock = DockStyle.Top; _noteTitle.Height = 28; _noteTitle.Font = new Font("Microsoft YaHei UI", 10F, FontStyle.Bold); _noteTitle.ForeColor = Color.FromArgb(60, 66, 72); right.Controls.Add(_noteTitle); Label hint = new Label(); hint.Dock = DockStyle.Top; hint.Height = 24; hint.Text = "边打边自动保存"; hint.ForeColor = Color.FromArgb(150, 155, 160); right.Controls.Add(hint); _note = new RichTextBox(); _note.Dock = DockStyle.Fill; _note.BorderStyle = BorderStyle.FixedSingle; _note.Font = new Font("Microsoft YaHei UI", 10F); _note.ScrollBars = RichTextBoxScrollBars.Vertical; _note.TextChanged += delegate { if (_loading) return; _saveTimer.Stop(); _saveTimer.Start(); }; right.Controls.Add(_note); right.Controls.SetChildIndex(_note, 0); right.Controls.SetChildIndex(hint, 1); right.Controls.SetChildIndex(_noteTitle, 2); Controls.Add(right); _grid = new CalGridPanel(); _grid.Dock = DockStyle.Fill; _grid.DayClicked += delegate { LoadNoteForSelected(); }; Controls.Add(_grid); _saveTimer = new Timer(); _saveTimer.Interval = 800; _saveTimer.Tick += delegate { _saveTimer.Stop(); SaveCurrent(); }; Load += delegate { GoMonth(); }; FormClosing += delegate { _saveTimer.Stop(); SaveCurrent(); }; // 停靠布局按 z-order 逆序计算:月历最先布局,否则工具栏盖住表头和第一行 Controls.SetChildIndex(_grid, 0); Controls.SetChildIndex(right, 1); Controls.SetChildIndex(bar, 2); // 标题控件在构造函数里创建,GoMonth 需要能拿到 _titleLabel = title; } Label _titleLabel; void GoMonth() { _grid.Year = _y; _grid.Month = _m; _grid.Grid = CalOps.BuildGrid(_y, _m); _grid.Marks = CalOps.NoteDays(_dir, _y, _m); if (_grid.Selected.Month != _m || _grid.Selected.Year != _y) { DateTime today = DateTime.Today; if (today.Year == _y && today.Month == _m) _grid.Selected = today; else _grid.Selected = new DateTime(_y, _m, 1); } _titleLabel.Text = CalOps.MonthTitle(_y, _m); int n = CalOps.CountMonth(_dir, _y, _m); _monthStat.Text = n == 0 ? "本月还没有备注" : "本月已写 " + n + " 天"; _grid.Invalidate(); LoadNoteForSelected(); } void LoadNoteForSelected() { DateTime d = _grid.Selected; if (d.Month != _m || d.Year != _y) { // 点到上/下月的格子:跟着翻过去 _y = d.Year; _m = d.Month; _grid.Year = _y; _grid.Month = _m; _grid.Grid = CalOps.BuildGrid(_y, _m); _grid.Marks = CalOps.NoteDays(_dir, _y, _m); _titleLabel.Text = CalOps.MonthTitle(_y, _m); int n = CalOps.CountMonth(_dir, _y, _m); _monthStat.Text = n == 0 ? "本月还没有备注" : "本月已写 " + n + " 天"; _grid.Invalidate(); } _loading = true; _note.Text = CalOps.LoadNote(_dir, d); _loading = false; _noteTitle.Text = d.ToString("yyyy-MM-dd") + " " + CalOps.WeekName(d.DayOfWeek) + (d.Date == DateTime.Today ? " (今天)" : ""); } void SaveCurrent() { DateTime d = _grid.Selected; if (d == DateTime.MinValue) return; string before = CalOps.LoadNote(_dir, d); string now = _note.Text; if (before == now) return; try { CalOps.SaveNote(_dir, d, now); _grid.Marks = CalOps.NoteDays(_dir, _y, _m); _grid.Invalidate(); int n = CalOps.CountMonth(_dir, _y, _m); _monthStat.Text = n == 0 ? "本月还没有备注" : "本月已写 " + n + " 天"; } catch (Exception ex) { MessageBox.Show("备注保存失败:" + ex.Message, "出错了"); } } void ExportMonth() { SaveCurrent(); SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "文本文件|*.txt"; dlg.FileName = _y + "-" + _m.ToString("00") + " 日历备注.txt"; if (dlg.ShowDialog() != DialogResult.OK) return; try { File.WriteAllText(dlg.FileName, CalOps.ExportMonth(_dir, _y, _m), new UTF8Encoding(false)); MessageBox.Show("已导出到:\r\n" + dlg.FileName, "完成"); } catch (Exception ex) { MessageBox.Show("导出失败:" + ex.Message, "出错了"); } } } public static class CalSelfTest { 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")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-cal-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 月天数 Check("2026 年 10 月 31 天", CalOps.DaysInMonth(2026, 10), 31); Check("2026 年 4 月 30 天", CalOps.DaysInMonth(2026, 4), 30); Check("2024 年闰年 2 月 29 天", CalOps.DaysInMonth(2024, 2), 29); Check("2023 年平年 2 月 28 天", CalOps.DaysInMonth(2023, 2), 28); Check("2000 年也是闰年", CalOps.DaysInMonth(2000, 2), 29); Check("1900 年不是闰年", CalOps.DaysInMonth(1900, 2), 28); Check("非法月份返回 0", CalOps.DaysInMonth(2026, 13), 0); Check("闰年判断 2024", CalOps.IsLeap(2024), true); Check("闰年判断 2100", CalOps.IsLeap(2100), false); // 周一开头 Check("周一索引为 0", CalOps.MondayIndex(DayOfWeek.Monday), 0); Check("周日索引为 6", CalOps.MondayIndex(DayOfWeek.Sunday), 6); Check("周六索引为 5", CalOps.MondayIndex(DayOfWeek.Saturday), 5); Check("2026-10-01 是周四", CalOps.FirstOfMonth(2026, 10).DayOfWeek, DayOfWeek.Thursday); // 网格 List grid = CalOps.BuildGrid(2026, 10); Check("固定 42 格", grid.Count, 42); Check("首格是 9 月 28 日(周一)", grid[0].ToString("yyyy-MM-dd"), "2026-09-28"); Check("末格是 11 月 8 日", grid[41].ToString("yyyy-MM-dd"), "2026-11-08"); Check("首格一定是周一", grid[0].DayOfWeek, DayOfWeek.Monday); Check("末格一定是周日", grid[41].DayOfWeek, DayOfWeek.Sunday); int inMonth = 0; for (int i = 0; i < grid.Count; i++) if (grid[i].Month == 10 && grid[i].Year == 2026) inMonth++; Check("本月天数在网格里齐了", inMonth, 31); Check("10 月 1 日恰在索引 3", grid[3].Day, 1); // 跨年翻月 int y = 2026, m = 1; CalOps.Shift(ref y, ref m, -1); Check("1 月往前是上一年 12 月", y + "-" + m, "2025-12"); y = 2026; m = 12; CalOps.Shift(ref y, ref m, 1); Check("12 月往后是次年 1 月", y + "-" + m, "2027-1"); y = 2026; m = 6; CalOps.Shift(ref y, ref m, -18); Check("连退 18 个月", y + "-" + m, "2024-12"); y = 2026; m = 6; CalOps.Shift(ref y, ref m, 30); Check("连进 30 个月", y + "-" + m, "2028-12"); Check("月标题格式", CalOps.MonthTitle(2026, 10), "2026 年 10 月"); Check("星期名", CalOps.WeekName(DayOfWeek.Monday), "周一"); // 备注读写 DateTime d1 = new DateTime(2026, 10, 19); Check("没写过时读空", CalOps.LoadNote(baseDir, d1), ""); Check("文件路径格式", Path.GetFileName(CalOps.NotePath(baseDir, d1)), "2026-10-19.txt"); CalOps.SaveNote(baseDir, d1, " 交季度报告 "); Check("写入后能读回(原样保留空格)", CalOps.LoadNote(baseDir, d1), " 交季度报告 "); Check("文件确实生成了", File.Exists(CalOps.NotePath(baseDir, d1)), true); CalOps.SaveNote(baseDir, new DateTime(2026, 10, 3), "体检"); CalOps.SaveNote(baseDir, new DateTime(2026, 10, 25), "朋友生日"); HashSet days = CalOps.NoteDays(baseDir, 2026, 10); Check("本月有备注 3 天", days.Count, 3); Check("含 19 号", days.Contains(19), true); Check("含 3 号", days.Contains(3), true); Check("不含 4 号", days.Contains(4), false); Check("其他月份为空", CalOps.NoteDays(baseDir, 2026, 11).Count, 0); Check("本月备注天数统计", CalOps.CountMonth(baseDir, 2026, 10), 3); // 空白备注 = 删文件 CalOps.SaveNote(baseDir, d1, " "); Check("空白备注删掉了文件", File.Exists(CalOps.NotePath(baseDir, d1)), false); Check("删掉后本月剩 2 天", CalOps.CountMonth(baseDir, 2026, 10), 2); Check("重复删空不抛异常", "ok", "ok"); // 导出 CalOps.SaveNote(baseDir, new DateTime(2026, 10, 19), "交季度报告"); string dump = CalOps.ExportMonth(baseDir, 2026, 10); Check("导出含月份标题", dump.IndexOf("2026 年 10 月 备注") == 0, true); Check("导出按日期升序(3 号在前)", dump.IndexOf("10-03") < dump.IndexOf("10-19"), true); Check("导出含备注正文", dump.IndexOf("体检") > 0, true); Check("导出含星期", dump.IndexOf("周一") > 0 || dump.IndexOf("周六") >= 0, true); Check("导出不含没备注的日子", dump.IndexOf("10-04") < 0, true); string empty = CalOps.ExportMonth(baseDir, 2026, 12); Check("空月份导出有提示", empty.IndexOf("还没写备注") > 0, true); // 文件名里的非法日期不进集合 File.WriteAllText(Path.Combine(baseDir, "2026-10-99.txt"), "x", new UTF8Encoding(false)); Check("99 号被忽略", CalOps.NoteDays(baseDir, 2026, 10).Contains(99), false); File.Delete(Path.Combine(baseDir, "2026-10-99.txt")); // 跨年导出 CalOps.SaveNote(baseDir, new DateTime(2027, 1, 1), "元旦"); Check("跨年备注可读", CalOps.LoadNote(baseDir, new DateTime(2027, 1, 1)), "元旦"); Check("跨年备注不进 2026 年 10 月集合", CalOps.NoteDays(baseDir, 2026, 10).Count, 3); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { Directory.Delete(baseDir, true); } catch { } } _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-deskcal.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(CalSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new DeskCalForm()); } } }