Installing Fonts programatically C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Drawing.Text; namespace itextcsharpDemo
{ /// <summary>
///
/// </summary>
public partial class Form4 : Form
{ int result = -1;
int error = 0; [DllImport("kernel32.dll", SetLastError = true)]
static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, // handle to destination window
uint Msg, // message
int wParam, // first message parameter
int lParam // second message parameter
);
[DllImport("gdi32")]
public static extern int AddFontResource(string lpFileName);
/// <summary>
///
/// </summary>
/// <param name="FontFileName"></param>
/// <param name="FontName"></param>
private void installFont(string FontFileName,string FontName)
{ string WinFontDir = "C:\\windows\\fonts";
//string FontFileName = "DS-Digital Bold Italic.TTF";
//string FontName = "DS-Digital Bold Italic";
int Ret;
int Res;
string FontPath;
const int WM_FONTCHANGE = 0x001D;
const int HWND_BROADCAST = 0xffff;
FontPath = WinFontDir + "\\" + FontName;
if (!File.Exists(FontPath))
{
File.Copy(FontFileName, FontPath); //System.Windows.Forms.Application.StartupPath + "\\DS-Digital Bold Italic.TTF"
Ret = AddFontResource(FontPath); Res = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
Ret = WriteProfileString("fonts", FontName + "(TrueType)", FontFileName);
}
} [DllImport("gdi32", EntryPoint = "AddFontResource")]
public static extern int AddFontResourceA(string lpFileName);
//[System.Runtime.InteropServices.DllImport("gdi32.dll")]
//private static extern int AddFontResource(string lpszFilename);
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
private static extern int CreateScalableFontResource(uint fdwHidden, string
lpszFontRes, string lpszFontFile, string lpszCurrentPath); //
[DllImport("gdi32.dll", EntryPoint = "RemoveFontResourceW", SetLastError = true)]
public static extern int RemoveFontResource([In][MarshalAs(UnmanagedType.LPWStr)]
string lpFileName); /// <summary>
/// Installs font on the user's system and adds it to the registry so it's available on the next session
/// Your font must be included in your project with its build path set to 'Content' and its Copy property
/// set to 'Copy Always'
/// win 10 没有权限 涂聚文注
/// </summary>
/// <param name="contentFontName">Your font to be passed as a resource (i.e. "myfont.tff")</param>
private static void RegisterFont(string contentFontName)
{
try
{
// Creates the full path where your font will be installed
var fontDestination = Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.Fonts), contentFontName); if (!File.Exists(fontDestination))
{
// Copies font to destination
System.IO.File.Copy(Path.Combine(System.IO.Directory.GetCurrentDirectory(), contentFontName), fontDestination); // Retrieves font name
// Makes sure you reference System.Drawing
PrivateFontCollection fontCol = new PrivateFontCollection();
fontCol.AddFontFile(fontDestination);
var actualFontName = fontCol.Families[0].Name; //Add font
AddFontResource(fontDestination);
//Add registry entry
Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts",
actualFontName, contentFontName, RegistryValueKind.String);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
} /// <summary>
///
/// </summary>
/// <param name="NombreFnt"></param>
/// <param name="RutaFnt"></param>
internal static void InstalarFuente(string NombreFnt, string RutaFnt)
{
string CMD = string.Format("copy /Y \"{0}\" \"%WINDIR%\\Fonts\" ", RutaFnt);
EjecutarCMD(CMD); System.IO.FileInfo FInfo = new System.IO.FileInfo(RutaFnt);
CMD = string.Format("reg add \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\" /v \"{0}\" /t REG_SZ /d {1} /f", NombreFnt, FInfo.Name);
EjecutarCMD(CMD);
}
/// <summary>
///
/// </summary>
/// <param name="Comando"></param>
public static void EjecutarCMD(string Comando)
{
System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo("cmd.exe");
Info.Arguments = string.Format("/c {0}", Comando);
Info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process.Start(Info);
}
/// <summary>
///
/// </summary>
public Form4()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form4_Load(object sender, EventArgs e)
{ }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
try
{ //汉仪篆书繁.ttf
//新蒂绿豆体.ttf
string fontname = System.Windows.Forms.Application.StartupPath + @"\font\汉仪篆书繁.ttf"; // "汉仪篆书繁.ttf";// //win 10 安装成功 Senty Pea 新蒂绿豆体
//windows/syste32/shell32.dll
//Shell32.Shell shell = new Shell32.Shell();
//Shell32.Folder fontFolder = shell.NameSpace(0x14);
//fontFolder.CopyHere(fontname); //没有权限
//RegisterFont(fontname); installFont(fontname, "汉仪篆书繁.ttf"); //无效
//result = AddFontResource(fontname);
//error = Marshal.GetLastWin32Error();
//if (error != 0)
//{
// MessageBox.Show(new Win32Exception(error).Message);
//} }
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
FontFamily[] fontList = new System.Drawing.Text.InstalledFontCollection().Families;
InstalledFontCollection installedFonts = new InstalledFontCollection();
List<FontList> list = new List<FontList>();
int id = 0;
foreach (FontFamily font in installedFonts.Families)
{
FontList l = new FontList();
l.FontName = font.Name;
l.FontId = id;
list.Add(l);
id++;
} listBox1.DataSource = list;
listBox1.ValueMember = "FontId";
listBox1.DisplayMember = "FontName"; }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.Items.Count > 0)
{
object o = this.listBox1.SelectedItem;
FontList od = new FontList();
od = o as FontList;
//MessageBox.Show(od.FontName);
this.textBox1.Text = od.FontName;
}
}
}
/// <summary>
///
/// </summary>
public class FontList
{
public int FontId { get; set; }
public string FontName { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal; namespace itextcsharpDemo
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{ //使用权限
var wi = WindowsIdentity.GetCurrent();
var wp = new WindowsPrincipal(wi); bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); //管理员权限 if (!runAsAdmin)
{
// It is not possible to launch a ClickOnce app as administrator directly,
// so instead we launch the app as administrator in a new process.
var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase); // The following properties run the new process as administrator
processInfo.UseShellExecute = true;
processInfo.Verb = "runas"; // Start the new process
try
{
Process.Start(processInfo);
}
catch (Exception)
{
// The user did not allow the application to run as administrator
MessageBox.Show("Sorry, but I don't seem to be able to start " +
"this program with administrator rights!");
} // Shut down the current process
Application.Exit();
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ManageForm());
}
}
}
}
https://stackoverflow.com/questions/14796162/how-to-install-a-windows-font-using-c-sharp
Installing Fonts programatically C#的更多相关文章
- EBS条形码打印
Oracle 提供两种方式实现 128 码的编码 第一种方式是使用 Reports Builder 实现对 128 码编码, 在 Metalink 305090.1[1] 有 比较详尽的描述,其中 ...
- $\TeX$ Gyre 字体安装过程与问题解决
目录 安装过程 1. 下载字体包 2. 安装字体 3. 测试范例文件 本文地址 https://www.cnblogs.com/oberon-zjt0806/p/13672426.html 本文只是一 ...
- bootstrap之google fonts
bootstrap之google fonts 在学习一个bootstrap时,看到了一行引用代码:@import url(http://fonts.googleapis.com/css?family= ...
- 【问题&解决】fonts/fontawesome-webfont.woff2 404 (Not Found)
问题: 虽然网页正常显示和运行,但是有2个字体文件出现404错误.像笔者这种强迫症是接受不了的. 解决: 因为笔者的服务器是虚拟主机,只需要在主机控制器平台添加对应的MIME类型即可. 这样服务器就支 ...
- installing mysql,this may take a few minutes,hold on plz wdcp卡住解决办法
centos6安装wdcp时make in progress卡住的解决办法 今天在一台centos6的vps上安装wdcp出现的这个问题,到安装程序滚动至下面这里时出现"卡死". ...
- CSS3 笔记三(Shadow/Text/Web Fonts)
CSS3 Shadow Effects text-shadow box-shadow 1> text-shadow The text-shadow property adds shadow to ...
- fonts.googleapis.com 加载慢的解决方法
把:fonts.googleapis.com 替换成 fonts.useso.com
- 最近在做外贸网站的时候,需要大量的字体来充实页面,就学习了怎么引用Google Fonts
第一步,FQ进入谷歌官方字体网站:https://fonts.google.com 妥妥的. 第二步,点击你所选择字体演示块的右上角的加号,然后你所选择的字体会形成引用链接以及你所要写的css样式. ...
- fonts.useso.com 访问变慢
fonts.useso.com 替换为 fonts.lug.ustc.edu.cn ajax.useso.com 替换为 ajax.lug.ustc.edu.cn the ...
随机推荐
- C# 交集、差集、并集、去重
Intersect 交集,Except 差集,Union 并集 , , , , }; , , , , , }; var jiaoJi = oldArray.Intersect(newArray).To ...
- GitHub 轻松提速教程
通过修改hosts文件来提速,获取github的IP地址 访问:https://www.ipaddress.com/ 网址 依次获取以下三个网址的IP github.com github.global ...
- spring框架学习笔记6:JDBC模板
JDBC模板:Spring中对数据库的操作. 这一部分对熟悉DBUtils的QueryRunner的开发者来说,非常简单 这是以前我简单写的dbutils的知识: http://www.cnblogs ...
- centos7配置apache服务
首先写下基本的步骤: 1.环境准备:关闭防火墙(不关闭无法访问,我这里只是简单的配置,实际部署项目应该会有具体的设置),关闭selinux(试过,不关闭也没事,一般都关闭) 配置 ip 2.安装软件包 ...
- Liferay7 BPM门户开发之15: Liferay开发体系简介
Liferay SDK 开发体系 主要分6种: Portlet Hook Theme Layout Templates Web Modules Ext Portlet :类似于servlet的web组 ...
- IIS服务器多站点 的 https证书使用443端口 解决方案
默认情况一个服务器的IIS只能绑定一个HTTPS也就是443端口 要实现多个站点对应HTTPS只能更改IIS配置 首先把每个站点分配个不同端口,如443.444.445…(证书一定要是多域的) 然后重 ...
- JAVA中的COPYONWRITE容器
Copy-On-Write简称COW,是一种用于程序设计中的优化策略.其基本思路是,从一开始大家都在共享同一个内容,当某个人想要修改这个内容的时候,才会真正把内容Copy出去形成一个新的内容然后再改, ...
- 课程四(Convolutional Neural Networks),第二 周(Deep convolutional models: case studies) —— 0.Learning Goals
Learning Goals Understand multiple foundational papers of convolutional neural networks Analyze the ...
- WebView使用_WebView监听网页下载_DownloadManager使用
最近在做一个较简单的项目:通过一个webview来显示一个网页的App 这个网页有下载的功能,关于这一功能需要用到两个知识点: 1.webview监听网页的下载链接.(webview默认情况下是没有开 ...
- Java NIO中的通道Channel(二)分散/聚集 Scatter/Gather
什么是Scatter/Gather scatter/gather指的在多个缓冲区上实现一个简单的I/O操作,比如从通道中读取数据到多个缓冲区,或从多个缓冲区中写入数据到通道: scatter(分散): ...