// 桌面便签 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:左边便签列表、右边随手写,边打边自动保存;可置顶、可调字号 // 边界:数据存 exe 同目录「便签数据」;exe 放在只读目录(如 Program Files)时自动退到 %APPDATA% // 原理:一条便签一个 txt,纯文本可直接用记事本打开、拷走、备份,不锁进数据库 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class NoteStore { public class Note { public string Id; public string Title; public string Body; public DateTime Modified; } private string _dir; public NoteStore(string dir) { _dir = dir; Directory.CreateDirectory(_dir); } public string DirPath { get { return _dir; } } public static string DefaultDir() { string exeDir = ""; try { exeDir = Path.GetDirectoryName(Application.ExecutablePath); } catch { } if (!string.IsNullOrEmpty(exeDir)) { try { string d = Path.Combine(exeDir, "便签数据"); Directory.CreateDirectory(d); string probe = Path.Combine(d, ".write-test"); File.WriteAllText(probe, "x", new UTF8Encoding(false)); File.Delete(probe); return d; } catch { } } string app = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GreenToolbox", "便签"); Directory.CreateDirectory(app); return app; } public List List() { List list = new List(); string[] files = Directory.GetFiles(_dir, "*.txt"); foreach (string f in files) { try { Note n = new Note(); n.Id = Path.GetFileNameWithoutExtension(f); n.Body = File.ReadAllText(f, new UTF8Encoding(false)); n.Title = TitleOf(n.Body); n.Modified = File.GetLastWriteTime(f); list.Add(n); } catch { } } list.Sort(delegate(Note a, Note b) { return b.Modified.CompareTo(a.Modified); }); return list; } public Note Create() { string id = DateTime.Now.ToString("yyyyMMdd-HHmmss-fff"); string path = Path.Combine(_dir, id + ".txt"); File.WriteAllText(path, "", new UTF8Encoding(false)); Note n = new Note(); n.Id = id; n.Title = TitleOf(""); n.Body = ""; n.Modified = DateTime.Now; return n; } public string Load(string id) { string path = Path.Combine(_dir, id + ".txt"); if (!File.Exists(path)) return ""; return File.ReadAllText(path, new UTF8Encoding(false)); } public void Save(string id, string text) { Directory.CreateDirectory(_dir); File.WriteAllText(Path.Combine(_dir, id + ".txt"), text ?? "", new UTF8Encoding(false)); } public void Delete(string id) { string path = Path.Combine(_dir, id + ".txt"); if (File.Exists(path)) File.Delete(path); } /* 列表里显示的名字:正文第一个非空行,太长截断 */ public static string TitleOf(string body) { if (string.IsNullOrEmpty(body)) return "空白便签"; string[] lines = body.Replace("\r\n", "\n").Split('\n'); foreach (string line in lines) { string t = line.Trim(); if (t.Length == 0) continue; if (t.Length > 20) t = t.Substring(0, 20) + "…"; return t; } return "空白便签"; } } public class StickyNoteForm : Form { private ListBox lst; private TextBox txt; private Button btnNew; private Button btnDel; private CheckBox chkTop; private ComboBox cbFont; private Label lblStatus; private Timer saveTimer; private NoteStore store; private List notes = new List(); private string currentId = ""; private bool loading = false; public StickyNoteForm() { store = new NoteStore(NoteStore.DefaultDir()); InitUi(); LoadList(null); } private void InitUi() { this.Text = "桌面便签 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(760, 520); this.MinimumSize = new Size(620, 400); this.StartPosition = FormStartPosition.CenterScreen; saveTimer = new Timer(); saveTimer.Interval = 800; saveTimer.Tick += new EventHandler(SaveTimerTick); Panel left = new Panel(); left.Location = new Point(0, 0); left.Size = new Size(210, 520); left.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; left.BackColor = Color.FromArgb(245, 249, 246); this.Controls.Add(left); Label lbNotes = new Label(); lbNotes.Text = "全部便签"; lbNotes.Location = new Point(12, 12); lbNotes.AutoSize = true; lbNotes.ForeColor = Color.FromArgb(120, 130, 124); left.Controls.Add(lbNotes); lst = new ListBox(); lst.Location = new Point(10, 36); lst.Size = new Size(190, 400); lst.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; lst.BorderStyle = BorderStyle.None; lst.BackColor = Color.FromArgb(245, 249, 246); lst.SelectedIndexChanged += new EventHandler(ListChanged); left.Controls.Add(lst); btnNew = new Button(); btnNew.Text = "新建"; btnNew.Location = new Point(10, 445); btnNew.Size = new Size(90, 30); btnNew.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; btnNew.Click += new EventHandler(NewClick); left.Controls.Add(btnNew); btnDel = new Button(); btnDel.Text = "删除"; btnDel.Location = new Point(108, 445); btnDel.Size = new Size(90, 30); btnDel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; btnDel.Click += new EventHandler(DelClick); left.Controls.Add(btnDel); Label lbHint = new Label(); lbHint.Text = "数据目录:" + store.DirPath; lbHint.Location = new Point(282, 486); lbHint.Size = new Size(460, 20); lbHint.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; lbHint.ForeColor = Color.FromArgb(150, 158, 153); lbHint.AutoEllipsis = true; this.Controls.Add(lbHint); chkTop = new CheckBox(); chkTop.Text = "窗口置顶"; chkTop.Location = new Point(228, 14); chkTop.AutoSize = true; chkTop.CheckedChanged += new EventHandler(TopChanged); this.Controls.Add(chkTop); Label lbFont = new Label(); lbFont.Text = "字号"; lbFont.Location = new Point(348, 14); lbFont.AutoSize = true; this.Controls.Add(lbFont); cbFont = new ComboBox(); cbFont.DropDownStyle = ComboBoxStyle.DropDownList; cbFont.Location = new Point(386, 10); cbFont.Size = new Size(70, 26); cbFont.Items.AddRange(new object[] { "11", "12", "14", "16", "18", "22" }); cbFont.SelectedIndex = 2; cbFont.SelectedIndexChanged += new EventHandler(FontChanged); this.Controls.Add(cbFont); lblStatus = new Label(); lblStatus.Location = new Point(480, 16); lblStatus.Size = new Size(260, 20); lblStatus.Anchor = AnchorStyles.Top | AnchorStyles.Right; lblStatus.TextAlign = ContentAlignment.MiddleRight; lblStatus.ForeColor = Color.FromArgb(0, 145, 88); this.Controls.Add(lblStatus); txt = new TextBox(); txt.Multiline = true; txt.ScrollBars = ScrollBars.Vertical; txt.AcceptsReturn = true; txt.BorderStyle = BorderStyle.None; txt.Location = new Point(228, 48); txt.Size = new Size(512, 424); txt.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; txt.Font = new Font("Microsoft YaHei UI", 14f); txt.TextChanged += new EventHandler(TextChangedHandler); this.Controls.Add(txt); this.FormClosing += new FormClosingEventHandler(ClosingHandler); } private void LoadList(string selectId) { loading = true; notes = store.List(); lst.BeginUpdate(); lst.Items.Clear(); foreach (NoteStore.Note n in notes) lst.Items.Add(n.Title); lst.EndUpdate(); if (notes.Count == 0) { NoteStore.Note n = store.Create(); notes.Insert(0, n); lst.Items.Add(n.Title); lst.SelectedIndex = 0; } else { int idx = 0; if (selectId != null) { for (int i = 0; i < notes.Count; i++) if (notes[i].Id == selectId) idx = i; } lst.SelectedIndex = idx; } loading = false; if (lst.SelectedIndex >= 0) ShowNote(lst.SelectedIndex); } private void ShowNote(int idx) { if (idx < 0 || idx >= notes.Count) return; currentId = notes[idx].Id; loading = true; txt.Text = store.Load(currentId); loading = false; lblStatus.Text = ""; this.Text = notes[idx].Title + " - 桌面便签"; } private void ListChanged(object sender, EventArgs e) { if (loading) return; Flush(); ShowNote(lst.SelectedIndex); } private void TextChangedHandler(object sender, EventArgs e) { if (loading) return; saveTimer.Stop(); saveTimer.Start(); } private void SaveTimerTick(object sender, EventArgs e) { saveTimer.Stop(); Flush(); } /* 立即落盘:切换便签、关窗、定时器到点都走这里 */ private void Flush() { if (currentId.Length == 0) return; try { store.Save(currentId, txt.Text); string title = NoteStore.TitleOf(txt.Text); int idx = lst.SelectedIndex; if (idx >= 0 && idx < lst.Items.Count && (string)lst.Items[idx] != title) { loading = true; lst.Items[idx] = title; loading = false; } lblStatus.Text = "已保存 " + DateTime.Now.ToString("HH:mm:ss"); } catch (Exception ex) { lblStatus.Text = "保存失败:" + ex.Message; } } private void NewClick(object sender, EventArgs e) { Flush(); NoteStore.Note n = store.Create(); LoadList(n.Id); txt.Focus(); } private void DelClick(object sender, EventArgs e) { if (lst.SelectedIndex < 0) return; string title = (string)lst.Items[lst.SelectedIndex]; if (MessageBox.Show("删除便签「" + title + "」?删了就找不回来了。", "确认删除", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) return; string id = currentId; currentId = ""; store.Delete(id); LoadList(null); } private void TopChanged(object sender, EventArgs e) { this.TopMost = chkTop.Checked; } private void FontChanged(object sender, EventArgs e) { float size = 14f; float.TryParse((string)cbFont.SelectedItem, out size); txt.Font = new Font("Microsoft YaHei UI", size); } private void ClosingHandler(object sender, FormClosingEventArgs e) { Flush(); } } // ───────────────────────── 自测 ───────────────────────── public static class StickySelfTest { 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-note-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); NoteStore store = new NoteStore(baseDir); Check("空目录列表为 0", store.List().Count, 0); NoteStore.Note n1 = store.Create(); Check("新建后有 1 条", store.List().Count, 1); Check("空便签标题", NoteStore.TitleOf(""), "空白便签"); Check("标题取第一行非空", NoteStore.TitleOf("\r\n \r\n买牛奶\r\n第二行"), "买牛奶"); Check("长标题截断", NoteStore.TitleOf("一二三四五六七八九十一二三四五六七八九十二十一").Length, 21); Check("截断带省略号", NoteStore.TitleOf("一二三四五六七八九十一二三四五六七八九十二十一").EndsWith("…"), true); store.Save(n1.Id, "买牛奶\r\n鸡蛋 6 个"); Check("保存后能读回", store.Load(n1.Id), "买牛奶\r\n鸡蛋 6 个"); Check("列表标题更新", store.List()[0].Title, "买牛奶"); // 再建一条,且更新时间必须更晚(列表按修改时间倒序) System.Threading.Thread.Sleep(1100); NoteStore.Note n2 = store.Create(); store.Save(n2.Id, "第二条便签"); List l2 = store.List(); Check("两条都在", l2.Count, 2); Check("最新一条排最前", l2[0].Id, n2.Id); // 覆盖保存(改内容) store.Save(n1.Id, "买牛奶(改成 2 盒)"); Check("覆盖保存生效", store.Load(n1.Id), "买牛奶(改成 2 盒)"); Check("文件是 UTF-8 无 BOM", File.ReadAllBytes(Path.Combine(baseDir, n1.Id + ".txt"))[0] != 0xEF, true); Check("正文里有中文", store.Load(n1.Id).IndexOf("买牛奶") == 0, true); // 删除 store.Delete(n1.Id); Check("删一条剩 1 条", store.List().Count, 1); Check("删掉的文件不存在", File.Exists(Path.Combine(baseDir, n1.Id + ".txt")), false); store.Delete(n1.Id); // 重复删不炸 Check("重复删除不抛异常", "ok", "ok"); // 特殊字符与多行 store.Save(n2.Id, "第1行\t制表符\n第2行 \"引号\" <标签> & 符号"); string round = store.Load(n2.Id); Check("制表符保留", round.IndexOf('\t') > 0, true); Check("尖括号保留", round.IndexOf("<标签>") > 0, true); Check("总数仍是 2 行", round.Replace("\r\n", "\n").Split('\n').Length, 2); // 路径可写性:默认目录能建 string def = NoteStore.DefaultDir(); Check("默认数据目录存在", Directory.Exists(def), true); Check("默认目录可写", HasWriteRight(def), true); // 不存在的 id 读回空串而不是抛异常 Check("读不存在的 id 返回空", store.Load("no-such-id"), ""); } 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-stickynote.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } static bool HasWriteRight(string dir) { try { string p = Path.Combine(dir, ".selftest-" + Guid.NewGuid().ToString("N") + ".tmp"); File.WriteAllText(p, "x"); File.Delete(p); return true; } catch { return false; } } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(StickySelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new StickyNoteForm()); } } }