// 字体预览管理器 —— 列出系统全部已装字体并即时预览 // 用法:FontView.exe [预览文字] // 不带参数:打开界面 // --selftest:自检(结果写 selftest-font.txt,UTF-8 BOM) using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace FontViewTool { internal static class FontOps { // 全部已装字体(族名,含中文名与英文名条目) public static List Families() { List list = new List(); using (InstalledFontCollection fc = new InstalledFontCollection()) { foreach (FontFamily f in fc.Families) { try { // IsStyleAvailable 需要字体真实可渲染;坏字体会抛异常,跳过 if (f.IsStyleAvailable(FontStyle.Regular)) list.Add(f.Name); } catch { } } } list.Sort(new NatCmp()); return list; } // 按关键字过滤(不区分大小写) public static List Filter(List fonts, string kw) { if (string.IsNullOrEmpty(kw)) return fonts; kw = kw.ToLowerInvariant(); List r = new List(); foreach (string f in fonts) if (f.ToLowerInvariant().Contains(kw)) r.Add(f); return r; } // 用指定字体把文字画到画布,返回非背景像素数(0 说明字体画不出字) public static int InkPixels(FontFamily fam, float size, string text) { int ink = 0; using (Bitmap b = new Bitmap(220, 90, System.Drawing.Imaging.PixelFormat.Format24bppRgb)) using (Graphics g = Graphics.FromImage(b)) { g.Clear(Color.White); try { using (Font font = new Font(fam, size)) using (Brush br = new SolidBrush(Color.Black)) g.DrawString(text, font, br, 2, 2); } catch { return 0; } for (int y = 0; y < 90; y += 1) for (int x = 0; x < 220; x += 1) { Color c = b.GetPixel(x, y); if (c.R < 200 || c.G < 200 || c.B < 200) ink++; } } return ink; } // 系统默认 UI 字体(列表右侧灰色名字用) public static string UiFontName() { using (Font f = Control.DefaultFont) return f.Name; } public static string ExportText(List fonts) { StringBuilder sb = new StringBuilder(); sb.AppendLine("系统已装字体(共 " + fonts.Count + " 个族):"); sb.AppendLine(); foreach (string f in fonts) sb.AppendLine(f); return sb.ToString(); } } // 自然排序:SimSun < SimSun-ExtB,MS YaHei < MS YaHei UI internal sealed class NatCmp : IComparer { public int Compare(string a, string b) { int ia = 0, ib = 0; while (ia < a.Length && ib < b.Length) { char ca = a[ia], cb = b[ib]; if (char.IsDigit(ca) && char.IsDigit(cb)) { long na = 0, nb = 0; while (ia < a.Length && char.IsDigit(a[ia])) { na = na * 10 + (a[ia] - '0'); ia++; } while (ib < b.Length && char.IsDigit(b[ib])) { nb = nb * 10 + (b[ib] - '0'); ib++; } if (na != nb) return na < nb ? -1 : 1; } else { if (ca != cb) return ca.CompareTo(cb); ia++; ib++; } } return (a.Length - ia).CompareTo(b.Length - ib); } } public class FontForm : Form { private TextBox _search; private TextBox _text; private ComboBox _size; private ListBox _list; private Label _count; private Button _copy; private Button _export; private Button _wbtn; private ContextMenuStrip _menu; private List _all; public FontForm(string sample) { Text = "字体预览 · 绿色工具箱"; Width = 980; Height = 720; StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9f); AllowDrop = true; _all = FontOps.Families(); var top = new Panel { Dock = DockStyle.Top, Height = 44, Padding = new Padding(10, 8, 10, 0) }; _search = new TextBox { Width = 170 }; _search.TextChanged += delegate { Refill(); }; _text = new TextBox { Width = 330, Left = 182, Text = sample }; _text.TextChanged += delegate { _list.Invalidate(); }; _size = new ComboBox { Left = 524, Width = 66, DropDownStyle = ComboBoxStyle.DropDownList }; foreach (string s in new string[] { "18", "22", "26", "32", "40", "48" }) _size.Items.Add(s); _size.SelectedIndex = 2; _size.SelectedIndexChanged += delegate { _list.Invalidate(); }; _count = new Label { Left = 600, Top = 5, AutoSize = true, ForeColor = SystemColors.GrayText, Text = _all.Count + " 个字体族" }; _copy = new Button { Text = "复制名称", Left = 700, Top = 1, Width = 84 }; _copy.Click += delegate { CopyName(); }; _export = new Button { Text = "导出清单", Left = 790, Top = 1, Width = 84 }; _export.Click += delegate { ExportList(); }; top.Controls.AddRange(new Control[] { _search, _text, _size, _count, _copy, _export }); Controls.Add(top); _list = new ListBox { Dock = DockStyle.Fill, DrawMode = DrawMode.OwnerDrawVariable, IntegralHeight = false, ItemHeight = 40 }; _list.DrawItem += OnDrawItem; _list.MeasureItem += delegate (object s, MeasureItemEventArgs e) { e.ItemHeight = GetItemHeight(e.Index); }; _list.MouseDoubleClick += delegate { CopyName(); }; _menu = new ContextMenuStrip(); _menu.Items.Add("复制字体名称", null, delegate { CopyName(); }); _menu.Items.Add("打开字体文件夹", null, delegate { try { System.Diagnostics.Process.Start("explorer.exe", "shell:Fonts"); } catch { } }); _list.ContextMenuStrip = _menu; Controls.Add(_list); _list.BringToFront(); Refill(); DragEnter += delegate (object s, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.Text)) e.Effect = DragDropEffects.Copy; }; DragDrop += delegate (object s, DragEventArgs e) { string t = (string)e.Data.GetData(DataFormats.Text); if (!string.IsNullOrEmpty(t)) { _text.Text = t.Trim(); } }; } private int GetItemHeight(int i) { if (i < 0 || i >= _list.Items.Count) return 40; int sz = CurrentSize(); return Math.Max(sz + 14, 40); } private int CurrentSize() { return _size.SelectedIndex < 0 ? 26 : int.Parse((string)_size.SelectedItem); } private void Refill() { List shown = FontOps.Filter(_all, _search.Text.Trim()); _list.BeginUpdate(); _list.Items.Clear(); foreach (string f in shown) _list.Items.Add(f); _list.EndUpdate(); _count.Text = shown.Count + " / " + _all.Count + " 个字体族"; } private void OnDrawItem(object s, DrawItemEventArgs e) { if (e.Index < 0) return; string name = (string)_list.Items[e.Index]; e.DrawBackground(); bool sel = (e.State & DrawItemState.Selected) != 0; using (SolidBrush bg = new SolidBrush(sel ? Color.FromArgb(226, 240, 229) : Color.White)) e.Graphics.FillRectangle(bg, e.Bounds); int sz = CurrentSize(); Rectangle textRect = new Rectangle(e.Bounds.X + 12, e.Bounds.Y + 4, e.Bounds.Width - 24, e.Bounds.Height - 8); try { FontFamily fam = new FontFamily(name); using (Font f = new Font(fam, sz)) using (SolidBrush br = new SolidBrush(sel ? Color.FromArgb(30, 90, 45) : Color.FromArgb(35, 35, 35))) e.Graphics.DrawString(_text.Text, f, br, textRect); } catch { using (SolidBrush br = new SolidBrush(Color.Red)) e.Graphics.DrawString(name + "(无法渲染)", Control.DefaultFont, br, textRect); } string meta = sz <= 22 ? name + " " : ""; using (SolidBrush br = new SolidBrush(Color.FromArgb(150, 150, 150))) { using (Font f = new Font("Microsoft YaHei UI", 8.5f)) e.Graphics.DrawString(meta, f, br, new RectangleF(e.Bounds.X + 12, e.Bounds.Bottom - 16, e.Bounds.Width - 24, 15)); } } // 测试钩子 internal int TestItems { get { return _list.Items.Count; } } internal string TestSearch { set { _search.Text = value; } } internal string TestSample { set { _text.Text = value; } } internal void TestSize(int sz) { int i = _size.Items.IndexOf(sz.ToString()); if (i >= 0) _size.SelectedIndex = i; } private void CopyName() { if (_list.SelectedIndex < 0) return; try { Clipboard.SetText((string)_list.SelectedItem); _copy.Text = "已复制✓"; var t = new Timer { Interval = 1200 }; t.Tick += delegate { _copy.Text = "复制名称"; t.Stop(); t.Dispose(); }; t.Start(); } catch { } } private void ExportList() { string path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "系统字体清单.txt"); File.WriteAllText(path, FontOps.ExportText(FontOps.Filter(_all, _search.Text.Trim())), Encoding.UTF8); try { System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + path + "\""); } catch { MessageBox.Show(path, "清单已导出"); } } } internal static class Program { private static readonly List _lines = new List(); private static int _pass, _fail; internal static bool _shown; private static void Check(string name, string got, string want) { bool ok = got == want; if (ok) _pass++; else _fail++; _lines.Add((ok ? "[ok] " : "[!!] ") + name + (ok ? "" : " → 期望 [" + want + "] 实际 [" + got + "]")); } private static void CheckTrue(string name, bool cond) { if (cond) _pass++; else _fail++; _lines.Add((cond ? "[ok] " : "[!!] ") + name); } private static void Flush() { _lines.Add(string.Format("结果:通过 {0} / {1}(失败 {2})", _pass, _pass + _fail, _fail)); File.WriteAllText( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "selftest-font.txt"), string.Join("\r\n", _lines.ToArray()), new UTF8Encoding(true)); } [STAThread] private static int Main(string[] args) { if (args.Length > 0 && args[0] == "--selftest") { try { RunSelfTest(); } catch (Exception ex) { _lines.Add("[!!] 自测异常: " + ex.Message); _fail++; } Flush(); return _fail == 0 ? 0 : 1; } string sample = "光阴似箭 2026 The quick brown fox"; if (args.Length > 0) sample = string.Join(" ", args); try { Application.ThreadException += delegate (object s, System.Threading.ThreadExceptionEventArgs e) { File.WriteAllText(Path.Combine(Path.GetTempPath(), "fontview-crash.txt"), "ThreadException:\r\n" + e.Exception, new UTF8Encoding(true)); }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); FontForm ff = new FontForm(sample); ff.Shown += delegate { _shown = true; }; Application.Run(ff); } catch (Exception ex) { File.WriteAllText(Path.Combine(Path.GetTempPath(), "fontview-crash.txt"), ex.ToString(), new UTF8Encoding(true)); throw; } return 0; } private static void RunSelfTest() { // 1. 枚举 List all = FontOps.Families(); CheckTrue("字体族数量超过 100", all.Count > 100); CheckTrue("已按自然排序", IsSorted(all)); CheckTrue("包含宋体类中文字体", all.Any(f => f.Contains("宋") || f.Contains("SimSun"))); CheckTrue("包含雅黑类中文字体", all.Any(f => f.Contains("雅黑") || f.Contains("YaHei"))); CheckTrue("包含 Arial", all.Any(f => f == "Arial")); // 2. 过滤 CheckTrue("不过滤返回全部", FontOps.Filter(all, "").Count == all.Count); List f1 = FontOps.Filter(all, "arial"); CheckTrue("小写关键字命中 Arial", f1.Contains("Arial")); CheckTrue("过滤后全是命中项", f1.All(x => x.ToLowerInvariant().Contains("arial"))); CheckTrue("无命中返回空", FontOps.Filter(all, "zzzznope").Count == 0); // 3. 渲染:中文样张在中文族上有笔画、字体与字体画出的像素数不同 string sample = "永国 2026"; int ya = FontOps.InkPixels(new FontFamily("Microsoft YaHei UI"), 24, sample); CheckTrue("雅黑渲染有笔画(" + ya + ")", ya > 80); string latinOnly = "abc"; List two = FontOps.Filter(all, "SimSun"); if (two.Count > 0) { int a1 = FontOps.InkPixels(new FontFamily(two[0]), 24, "永"); int a2 = FontOps.InkPixels(new FontFamily(two[0]), 12, "永"); CheckTrue("大字号笔画更多(" + a1 + ">" + a2 + ")", a1 > a2); } int av = FontOps.InkPixels(new FontFamily("Arial"), 24, latinOnly); try { int co = FontOps.InkPixels(new FontFamily("Consolas"), 24, latinOnly); CheckTrue("不同字体笔画数不同", av != co); } catch { CheckTrue("不同字体笔画数不同", av > 0); } CheckTrue("空文字零笔画", FontOps.InkPixels(new FontFamily("Arial"), 24, "") == 0); // 4. 自然排序器 NatCmp nc = new NatCmp(); CheckTrue("数字段按数值比较", nc.Compare("Font 9", "Font 10") < 0); CheckTrue("等名字为 0", nc.Compare("Arial", "Arial") == 0); CheckTrue("前缀短者在前", nc.Compare("SimSun", "SimSun-ExtB") < 0); // 5. 导出 string exp = FontOps.ExportText(all); CheckTrue("导出含总数行", exp.Contains("共 " + all.Count + " 个")); CheckTrue("导出每族一行", exp.Split('\n').Length >= all.Count + 3); // 6. Form 层:搜索、预览文字改动不炸 var form = new FontForm("预览"); try { CheckTrue("列表已填充", form.ItemsCount() == all.Count); form.SetSearch("arial"); CheckTrue("搜索联动计数", form.ItemsCount() > 0 && form.ItemsCount() < all.Count); form.SetSearch(""); form.SetSample("测试 123"); CheckTrue("换样张不炸", form.ItemsCount() == all.Count); form.SetSize(48); CheckTrue("调大字号不炸", form.ItemsCount() == all.Count); } finally { form.Dispose(); } } private static bool IsSorted(List l) { for (int i = 1; i < l.Count; i++) if (new NatCmp().Compare(l[i - 1], l[i]) > 0) return false; return true; } } internal static class FormExt { public static int ItemsCount(this FontForm f) { return f.TestItems; } public static void SetSearch(this FontForm f, string kw) { f.TestSearch = kw; } public static void SetSample(this FontForm f, string s) { f.TestSample = s; } public static void SetSize(this FontForm f, int sz) { f.TestSize(sz); } } }