RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
如何C#程序安装windows系统字体-创新互联

如何C#程序安装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);

 /// 
 /// 安装字体
 /// 
 /// 字体文件全路径
 /// 是否成功安装字体
 /// 不是管理员运行程序
 /// 字体安装失败
 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;
 }

网站栏目:如何C#程序安装windows系统字体-创新互联
分享网址:http://scyingshan.cn/article/dhiigg.html