首页 > 编程语言 >C#自动安装字体

C#自动安装字体

时间:2023-08-18 11:34:18浏览次数:35  
标签:文件 string C# System 字体 new 安装

在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
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

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, 0, MeAdd, bytes.Length);
    pfc.AddMemoryFont(MeAdd, bytes.Length);
    return new Font(pfc.Families[0], 15, FontStyle.Regular);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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[0], 24, FontStyle.Regular, GraphicsUnit.Point, 0);//font就是通过文件创建的字体对象
    return font;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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

/// <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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

/// <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;
}

标签:文件,string,C#,System,字体,new,安装
From: https://www.cnblogs.com/webenh/p/17639971.html

相关文章

  • Activity对话框主题样式
    <stylename="DialogTheme"parent="@style/Theme.AppCompat.Dialog"><itemname="windowNoTitle">true</item><itemname="android:windowIsFloating">true</item><......
  • linux shell wc统计文件行数
    语法:wc[选项]文件…说明:该命令统计给定文件中的字节数、字数、行数。如果没有给出文件名,则从标准输入读取。wc同时也给出所有指定文件的总统计数。字是由空格字符区分开的最大字符串。该命令各选项含义如下:-c统计字节数。-l统计行数。-w统计字数。这些选项可以......
  • Ai 2020下载-Adobe Illustrator CC 2020官方版下载 系列软件
    ai是一款广泛应用于出版、多媒体和在线图像的工业标准矢量插画的软件。AdobeIllustratorCS5即ai,ai除了能够绘制高精度的矢量图之外,也可以为线稿提供较高的精度和控制,适合生产任何小型设计到大型的复杂项目!软件地址:看置顶贴AdobeIllustrator2020的功能特点:最新的插图行业标准的......
  • AI全版本下载 AI最新版安装包下载(附安装教程) 系列软件
    illustrator2022v26.0.1是由Adobe公司设计的一款全球最为知名的矢量图形设计软件,该软件为用户们提供了大量的图形所需要的常用工具和强大的功能,如图标设计、徽标、字体、颜色、图标、壁纸、信息图设计等等,可以帮助设计师大大提高工作效率,并且操作也是非常的简单,现已广泛应用于广......
  • mac电脑lr软件中文版-Lightroom2022mac永久版 系列软件
    AdobeLightroom2021(简称LR)是一款专业的数字照片处理和管理软件,可以用于调整、编辑、组织和分享数码照片。它主要用于摄影爱好者、职业摄影师和图像编辑师等领域。软件地址:看置顶贴使用“颜色分级”对阴影、中间色调和高光进行新的受控调整,借助中间色调、阴影和高光的强大颜色控件......
  • cerebro+openresty拦截
    通过openresty拦截掉危险的操作。配置文件如下:$catdocker-compose.yamlversion:'3'networks:monitor:driver:bridgeservices:cerebro:image:lmenezes/cerebrocontainer_name:cerebrohostname:cerebrorestart:a......
  • c# system.speech语音识别
    在.net4.0 添加引用system.speech.dllusingSystem.Speech.Recognition;//创建语音识别引擎SpeechRecognitionEnginerecognitionEngine=newSpeechRecognitionEngine();//创建一组语音识别的语法约束选择......
  • libpcap数据包格式
    pcap文件格式如下:24字节文件头+(16字节pcap数据包信息+数据包)*n。Libpcap的官方网站是http://www.tcpdump.org/,该项目和Tcpdump项目是同一个团队维护。Libpcap是一个平台独立的数据包捕获开发包,制定了数据包离线存储的事实标准。接下来我们就介绍一下该标准。文件头说明:1、标......
  • apache开启php的伪静态模式,出现No input file specified
    Thinkphp教程中提供的APACHE伪静态模式出现Noinputfilespecified,打开.htaccess在RewriteRule后面的index.php教程后面添加一个“?”完整代码如下.htaccessRewriteEngineonRewriteCond$1!^(index.php|images|robots.txt)RewriteRule^(.*)$/index.php?/$1[QSA,PT,L......
  • Prism IoC 依赖注入
    现有2个项目,SinglePageApp是基于Prism创建的WPF项目,框架使用的是Prism.DryIoc,SinglePageApp.Services是C#类库,包含多种服务,下面通过使用Prism中的依赖注入方式,将自定义的服务注册到SinglePageApp项目中。 1.认识Prism中的依赖注入Prism项目中的App继承于PrismAppl......