必须先用PrivateFontCollection.AddFontFile()注册字体文件,再通过Families获取真实字体名创建Font;注册后需妥善Dispose防GDI句柄泄漏;WinForms与WPF加载机制完全不同,不可混用。

加载字体文件前必须注册到当前进程,否则 PrivateFontCollection 无法识别
Windows GDI+ 不会自动把磁盘上的 .ttf/.otf 文件变成可用字体,得手动“告诉”它这个字体存在。核心是用 PrivateFontCollection 的 AddFontFile() 方法注册,且注册后字体名不是文件名,而是字体内部的「真实名称」(比如 "Source Code Pro" 而非 "SourceCodePro-Regular.ttf")。
常见错误:直接用 new Font("xxx.ttf", 12) —— 这完全无效,Font 构造函数只认已注册或系统安装的字体名。
- 注册必须在使用前完成,且同一个字体文件不能重复调用
AddFontFile(),否则可能引发 GDI+ 错误 - 注册后的字体仅对当前
PrivateFontCollection实例有效,不能跨实例共享 - 字体文件路径需确保可读,相对路径建议用
Assembly.GetExecutingAssembly().Location配合Path.GetDirectoryName()定位
从 PrivateFontCollection 获取字体名要用 Families 属性遍历
字体文件加载成功后,你并不能直接知道它叫什么。Windows 字体名藏在文件元数据里,得靠 PrivateFontCollection.Families 拿出来看。不同字体文件可能有多个家族(比如 Regular、Bold、Italic 共存于一个 .ttf),也可能一个文件只含一个变体。
常见错误:硬编码字体名,比如写死 new Font("MyCustomFont", 12),但实际文件里注册进来的是 "My Custom Font" 或 "MyCustomFont-Rg",导致 FontFamily.IsStyleAvailable() 返回 false。
- 调试时务必打印
collection.Families.Select(f => f.Name)看真实名称 - 同一个
FontFamily可能不支持所有样式(如只有 Regular,没有 Bold),用IsStyleAvailable(FontStyle.Bold)检查再创建 - 注意大小写和空格——GDI+ 对字体名区分大小写
动态字体必须手动管理生命周期,不释放会导致 GDI 句柄泄漏
PrivateFontCollection 底层持有 GDI+ 字体资源,.NET 不会自动回收。如果反复加载同一字体又不释放,进程的 GDI 句柄数会持续上涨,最终触发 OutOfMemoryException 或界面绘制失败。
典型现象:程序跑几小时后,Label 文字突然不显示,或 Graphics.DrawString() 报 "Parameter is not valid" 错误。
- 注册字体的
PrivateFontCollection实例应作为类字段长期持有,避免频繁 new + dispose - 不要在每次绘图时都 new 一个
PrivateFontCollection并加载字体 - 窗体关闭或模块卸载时,显式调用
privateFontCollection.Dispose() - 若字体需全局使用,建议封装成静态单例,但要注意线程安全(
PrivateFontCollection非线程安全)
WPF 和 WinForms 处理方式完全不同,别混用
WinForms 依赖 GDI+,必须走 PrivateFontCollection;而 WPF 使用 DirectWrite,加载方式是往 Application.Current.Resources 注册 FontFamily,或者用 FontSource 加载流。两者 API 完全不兼容。
常见错误:在 WPF 项目里抄 WinForms 的 AddFontFile() 代码,结果编译通过但运行时无效果;或在 WinForms 里尝试用 new FontFamily(new Uri(...)),抛出 NotSupportedException。
- WinForms 示例关键行:
privateFontCollection.AddFontFile(@"fonts\custom.ttf"); var family = privateFontCollection.Families[0]; var font = new Font(family, 12); - WPF 正确做法:把字体文件设为
Resource构建操作,然后用new FontFamily(new Uri("pack://application:,,,/"), "./fonts/#Custom Font") - 跨平台(如 Avalonia)另有一套机制,不适用上述任一方案
字体名匹配不准、句柄没释放、UI 框架选错——这三个点卡住的人最多。尤其注意调试时别只看文件名,得进 Families 里翻真实名称。










