在Windows系统中,原有自带的字体样式有限,有时候我们的程序会使用到个别稀有或系统不自带的字体。因此我们需要将字体打包到程序中,当程序启动时,检测系统是否有该字体,如果没有则安装该字体,也可以动态加载字体。

  1.1、使用代码安装字体

  注意:安装字体时,需要windows的管理员权限。

 [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(System.Windows.Forms.Application.StartupPath + "\\font\\" + FontFileName, FontPath); //font是程序目录下放字体的文件夹
//将某路径下的字体拷贝到系统字体文件夹下
File.Copy(fontFilePath, fontPath); //font是程序目录下放字体的文件夹
AddFontResource(fontPath); //Res = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
//WIN7下编译会出错,不清楚什么问题。注释就行了。
//安装字体
WriteProfileString("fonts", Path.GetFileNameWithoutExtension(fontFilePath) + "(TrueType)", Path.GetFileName(fontFilePath));
}
}
catch (Exception ex)
{
throw new Exception(string.Format($"[{Path.GetFileNameWithoutExtension(fontFilePath)}] 字体安装失败!原因:{ex.Message}" ));
}
return true;
}

 1.2、从项目资源文件中加载字体

  该方法需要开发者将字体文件以资源的形式放入项目资源文件中。不用安装到字体库中,其他程序如果需要使用,就需要自己安装或者加载。此时可以使用以下代码创建程序所需字体:

/// <summary>
/// 如何使用资源文件中的字体,无安装无释放
/// </summary>
/// <param name="bytes">资源文件中的字体文件</param>
/// <returns></returns>
public Font GetResoruceFont(byte[] bytes)
{
System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
IntPtr MeAdd = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, , MeAdd, bytes.Length);
pfc.AddMemoryFont(MeAdd, bytes.Length);
return new Font(pfc.Families[], , FontStyle.Regular);
}

 1.3、加载某个字体文件,加载字体

  设置好某个字体的路径,然后加载字体文件,从而创建字体。不用安装到字体库中,其他程序如果需要使用,就需要自己安装或者加载。

/// <summary>
/// 通过文件获取字体
/// </summary>
/// <param name="filePath">文件全路径</param>
/// <returns>字体</returns>
public Font GetFontByFile(string filePath)
{
//程序直接调用字体文件,不用安装到系统字库中。
System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
pfc.AddFontFile(filePath);//字体文件的路径
Font font = new Font(pfc.Families[], , FontStyle.Regular, GraphicsUnit.Point, );//font就是通过文件创建的字体对象
return font;
}

2、检测系统中是否包含某种字体

  对于检测是否已经安装了某种字体的方法有很多,这里只介绍检测是否有该文件的方式:

/// <summary>
/// 检查字体是否存在
/// </summary>
/// <param name="familyName">字体名称</param>
/// <returns></returns>
public static bool CheckFont(string familyName)
{
string FontPath = Path.Combine(System.Environment.GetEnvironmentVariable("WINDIR"), "fonts", Path.GetFileName(familyName));
//检测系统是否已安装该字体
return File.Exists(FontPath);
}

  检测某种字体样式是否可用:

/// <summary>
/// 检测某种字体样式是否可用
/// </summary>
/// <param name="familyName">字体名称</param>
/// <param name="fontStyle">字体样式</param>
/// <returns></returns>
public bool CheckFont(string familyName, FontStyle fontStyle= FontStyle.Regular )
{
InstalledFontCollection installedFontCollection = new InstalledFontCollection();
FontFamily[] fontFamilies = installedFontCollection.Families;
foreach(var item in fontFamilies)
{
if (item.Name.Equals(familyName))
{
return item.IsStyleAvailable(fontStyle);
}
}
return false;
}

windows系统下,在C#程序中自动安装字体的更多相关文章

  1. 在打包程序中自动安装SQL Server数据库 .

    原文:在打包程序中自动安装SQL Server数据库 . 1.创建安装项目“Setup1”安装项目 在“文件”菜单上指向“添加项目”,然后选择“新建项目”. 在“添加新项目”对话框中,选择“项目类型” ...

  2. windows系统下简单nodej.s环境配置 安装

    国内目前关注最高,维护最好的一个关于nodejs的网站应该是http://www.cnodejs.org/ windows系统下简单nodejs环境配置. 第一步:下载安装文件 下载地址:官网 htt ...

  3. windows系统下简单node.js环境配置 安装

    国内目前关注最高,维护最好的一个关于nodejs的网站应该是http://www.cnodejs.org/ windows系统下简单nodejs环境配置. 第一步:下载安装文件 下载地址:官网 htt ...

  4. Windows系统下在Git Bash中把文件内容复制到剪贴板的命令

    众所周知,在OS系统中,复制文件内容到剪贴板(比如复制公钥到剪贴板)的命令是: pbcopy < ~/.ssh/id_rsa.pub 在Win7或者Win10下这条命令就没用了.可以这样: cl ...

  5. Windows系统下运行某些程序时缺少“Msflxgrd.ocx”的解决方法

    出现这样的错误就是系统缺少相应的库文件,我们安装即可. 下载Msflxgrd.ocx,这里提供一个下载网址:https://www.ocxme.com/files/msflxgrd_ocx 64位系统 ...

  6. windows系统下python2.7.14版本的安装

    [前言] 本文主要对window下如何安装Python进行图解说明. [正文] 步骤一 从官网下载相应的版本(本文以2.7.14为例),下载地址:https://www.python.org/down ...

  7. windows系统下mysql-8.0.13-winx64(zip安装)

    一.下载地址: http://mirrors.163.com/mysql/Downloads/MySQL-8.0/mysql-8.0.13-winx64.zip 二.安装: 1.解压: mysql根路 ...

  8. Python3.x:pyodbc连接Sybase数据库操作(Windows系统下DNS模式)

    Python3.x:pyodbc连接Sybase数据库操作(Windows系统下DNS模式) 一.安装模块pyodbc pip install pyodbc 二.配置odbc数据源 (1).windo ...

  9. 在Windows系统下用命令把应用程序添加到系统服务

    在Windows系统下用命令把应用程序添加到系统服务,使用SC命令. 加入服务格式如下:sc create ServiceName binPath= 程序路径 start= auto(等号后面的空格是 ...

随机推荐

  1. HDU 3466 Proud Merchants 带有限制的01背包问题

    HDU 3466 Proud Merchants 带有限制的01背包问题 题意 最近,伊萨去了一个古老的国家.在这么长的时间里,它是世界上最富有.最强大的王国.因此,即使他们的国家不再那么富有,这个国 ...

  2. Tomcat控制台中文乱码

    参考:https://blog.csdn.net/zhaoxny/article/details/79926333 1.找到${CATALINA_HOME}/conf/logging.properti ...

  3. HNUSTOJ-1698 送外卖(TSP问题 + 状态压缩DP)

    1698: 送外卖 时间限制: 1 Sec  内存限制: 128 MB提交: 123  解决: 28[提交][状态][讨论版] 题目描述 在美团和饿了么大行其道的今天,囊中羞涩的小周和小美,也随大流加 ...

  4. Dire Wolf——HDU5115(区间DP)

    题意 就是有一对狼,每个狼有初始的攻击力,并且还能给左右两边的狼提供攻击力加成,当冒险家杀死一头狼的时候他也会受到这个狼目前攻击力的伤害 实例解析 33 5 78 2 0 有三头狼,刚开始第二头狼给他 ...

  5. P2220 [HAOI2012]容易题

    传送门 首先 $(\sum_{i=1}^{n}a_i)(\sum_{i=1}^{m}b_i)$ 展开以后包含了所有 $ab$ 两两相乘的情况并且每种组合只出现一次 发现展开后刚好和题目对序列价值的定义 ...

  6. js函数调用的几种方法

    js的函数调用会免费奉送两个而外的参数就是 this 和 arguments .arguments是参数组,他并不是一个真实的数组,但是可以使用.length方法获得长度. 书上有说4中调用方式: 方 ...

  7. flutter 布局简介

    import 'package:flutter/material.dart'; class LayoutDemo extends StatelessWidget { @override Widget ...

  8. socket keepalive 服务端异常断线

    异常断线  客户端检测不到  没有重连

  9. Maven项目的一些依赖

    Maven构建的Spring项目需要哪些依赖? <!-- Spring依赖 --> <!-- 1.Spring核心依赖 --> <dependency> <g ...

  10. 二进制sersync部署安装

    一.为什么要用rsync+sersync架构? 1.sersync是基于inotify开发的,类似于inotify-tools的工具 2.sersync可以记录下被监听目录中发生变化的(包括增加.删除 ...