You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#应用发布后嵌入自定义字体以确保多设备正常显示

在C#项目中嵌入自定义字体并加载的解决方案

一、准备字体文件并配置项目

  • 将需要的字体文件(如.ttf/.otf)复制到项目目录,建议新建Fonts文件夹统一存放
  • 在Visual Studio中右键项目 → 添加 → 现有项,选中字体文件
  • 在属性窗口设置:
    • 生成操作:设为Embedded Resource(WinForms)或Resource(WPF)
    • 复制到输出目录:设为如果较新则复制(WinForms)或不复制(WPF)

二、WinForms项目加载字体代码示例

using System.Drawing.Text;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

private PrivateFontCollection _customFonts = new PrivateFontCollection();

private void Form_Load(object sender, EventArgs e)
{
    // 嵌入资源名称格式:命名空间.文件夹名.字体文件名,例如"MyProject.Fonts.MyCustomFont.ttf"
    string resourceName = "MyProject.Fonts.MyCustomFont.ttf";
    using (Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
    {
        if (fontStream == null) return;

        byte[] fontBytes = new byte[fontStream.Length];
        fontStream.Read(fontBytes, 0, (int)fontStream.Length);
        
        IntPtr fontPtr = Marshal.AllocCoTaskMem(fontBytes.Length);
        Marshal.Copy(fontBytes, 0, fontPtr, fontBytes.Length);
        _customFonts.AddMemoryFont(fontPtr, fontBytes.Length);
        Marshal.FreeCoTaskMem(fontPtr);
    }

    // 给控件应用字体
    if (_customFonts.Families.Length > 0)
    {
        yourLabel.Font = new Font(_customFonts.Families[0], 14, FontStyle.Regular);
    }
}

排查提示:可通过Assembly.GetExecutingAssembly().GetManifestResourceNames()输出所有嵌入资源,确认字体的资源名称是否正确。

三、WPF项目加载字体方案

1. XAML声明式加载

在App.xaml中添加字体资源:

<Application.Resources>
    <!-- pack URI格式:pack://application:,,,/文件夹名/字体文件名#字体内部名称 -->
    <FontFamily x:Key="CustomFont">pack://application:,,,/Fonts/MyCustomFont.ttf#My Custom Font</FontFamily>
</Application.Resources>

在控件中引用:

<Label FontFamily="{StaticResource CustomFont}" FontSize="14">测试文本</Label>

注意:#后的是字体内部名称(不是文件名),可右键字体文件→预览,查看顶部显示的字体名称。

2. 代码动态加载

var fontUri = new Uri("pack://application:,,,/Fonts/MyCustomFont.ttf");
var customFont = new FontFamily(fontUri, "#My Custom Font");
yourLabel.FontFamily = customFont;

四、常见排查要点

  • 确认字体内部名称与代码/XAML中使用的一致
  • 检查嵌入资源的命名空间、路径是否匹配
  • 发布后验证输出文件中包含字体资源(WinForms嵌入到exe/dll,WPF资源打包在程序集内)

内容的提问来源于stack exchange,提问作者zazo mama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 04:43:14