WPF如何使用外部字体

当我们所使用的字体,系统不存在怎么办?

一种方式就是给系统安装该字体,这种方式安装的字体能够全局生效。

控制面板中可以看到本机已经安装了哪些字体:

第二种方法就是免安装,直接加载字体资源。

一. 全局安装:

cs 复制代码
[DllImport("kernel32.dll", SetLastError = true)]
        public static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);

        [DllImport("gdi32")]
        public static extern int AddFontResource(string lpFileName);

        /// <summary>
        /// 安装字体
        /// </summary>
        /// <param name="fontFilePath">字体文件全路径</param>
        /// <returns>是否成功安装字体</returns>
        /// <exception cref="UnauthorizedAccessException">不是管理员运行程序</exception>
        /// <exception cref="Exception">字体安装失败</exception>
        public static bool InstallFont(string fontFilePath)
        {
            try
            {
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();

                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                //判断当前登录用户是否为管理员
                if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator) == false)
                {
                    throw new UnauthorizedAccessException("当前用户无管理员权限,无法安装字体。");
                }
                //获取Windows字体文件夹路径
                string fontPath = Path.Combine(System.Environment.GetEnvironmentVariable("WINDIR"), "fonts", Path.GetFileName(fontFilePath));
                //检测系统是否已安装该字体
                if (!File.Exists(fontPath))
                {                    
                    File.Copy(fontFilePath, fontPath); //font是程序目录下放字体的文件夹
                    AddFontResource(fontPath);
                    //安装字体
                    WriteProfileString("fonts", Path.GetFileNameWithoutExtension(fontFilePath) + "(TrueType)", Path.GetFileName(fontFilePath));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format($"[{Path.GetFileNameWithoutExtension(fontFilePath)}] 字体安装失败!原因:{ex.Message}"));
            }
            return true;
        }

这种方案需要管理员权限才能安装,并且安装的字体路径在不同(win7,win10,win11)的操作系统里面不尽相同。整个安装过程相对会麻烦一些,卸载软件的时候,还得考虑需不需要卸载我们软件安装的字体。于是我们有了第二种方案,免安装使用字体!

字体引入方式:

使用xaml方式:

html 复制代码
<TextBlock Text="text1">
    <TextBlock.FontFamily>
        <FontFamily>/程序集名称;component/Font/字体文件名#字体名称</FontFamily>
    </TextBlock.FontFamily>
</TextBlock>

后台代码引用:

cs 复制代码
textBlock.FontFamily=new FontFamily(new Uri("/程序集名称;component/Font/字体文件名"),"字体名称")

这里需要注意下,引入字体的路径是字体文件的相对或绝对路径,通过 #号连接 字体名称来引入。

相关推荐
Maybe_ch1 天前
深度解析 WPF 线程模型:告别 UI 卡死,掌握 Dispatcher 核心机制
ui·wpf
code bean1 天前
【Halcon 】用 Halcon 实现涂抹:Region、仿射变换与 WPF 交互
wpf·交互·halcon
白露与泡影2 天前
Spring Cloud进阶--分布式权限校验OAuth2
分布式·spring cloud·wpf
枫叶丹42 天前
【HarmonyOS 6.0】ArkData 分布式数据对象新特性:资产传输进度监听与接续传输能力深度解析
开发语言·分布式·华为·wpf·harmonyos
一念春风2 天前
智能文字识别工具(AI)
开发语言·c#·wpf
故事不长丨2 天前
WPF MvvmLight 超详细使用教程
c#·wpf·mvvm·mvvmlight
IT小哥哥呀4 天前
基于windows的个人/团队的时间管理工具
windows·c#·wpf·时间管理
sczmzx4 天前
Cefsharp.WPF高分辨率下崩溃问题解决方案
wpf
cjp5605 天前
023.WPF combox控件数据绑定
wpf
Scout-leaf5 天前
WPF新手村教程(七)—— 终章(MVVM架构初见杀)
c#·wpf