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 ...
随机推荐
- vuejs-devtools
先看看http://www.cnblogs.com/zhnaglei/p/7121482.html 这里的方法. 如果出现vue.js not detected之类的错误.试试用调试模式,就是用npm ...
- MyBatis 源码分析 - 配置文件解析过程
* 本文速览 由于本篇文章篇幅比较大,所以这里拿出一节对本文进行快速概括.本篇文章对 MyBatis 配置文件中常用配置的解析过程进行了较为详细的介绍和分析,包括但不限于settings,typeAl ...
- CPU Hardwar
GPU负责把线程块分配到各个SM上处理. CUDA对申请的线程块何时运行,以及在哪个SM上运行是没有保证的.这恰好是GPU的优势,这种方式带来了灵活性,不需程序根据SM的数量去配置程序. 但是一个bl ...
- LeetCode--No.004 Median of Two Sorted Arrays
4. Median of Two Sorted Arrays Total Accepted: 104147 Total Submissions: 539044 Difficulty: Hard The ...
- Golang Struct 声明和使用
Golang Struct 声明和使用 Go可以声明自定义的数据类型,组合一个或多个类型,可以包含内置类型和用户自定义的类型,可以像内置类型一样使用struct类型 Struct 声明 具体的语法 t ...
- Redis主从和集群
主从概念 一个master可以拥有多个slave,一个slave又可以拥有多个slave.如此下去,形成了强大的多级服务器集群架构. master用写数据,经统计:网站的读写比率是10:1 通过主从分 ...
- Spark之GraphX的Graph_scala学习
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreem ...
- Intellij-插件安装-JRebel热部署插件安装
环境介绍: Win7.JDK1.8.maven+jetty插件.SpringMVC.Intellij IDEA 2018.1.2 安装插件: 在线安装: Settings --> Plugins ...
- C# 中集合类型需要按多个条件排序
在 C# (.net 3.5 之后) 中集合是可以通过 OrderBy() 和 OrderByDescending()方法来进行排序的,如果需要集合中的元素是对象,还可以通过 Lambda表达式进行按 ...
- EOS商业落地利器:多签名操作与应用
eos主网上线在即,它之所以能受到各方青睐,主要是看中了它在未来商业应用落地的潜力.在这期间,完善的账户与权限系统是必要条件. 关键字:eos,账户,钱包,权限,多重签名,eosio.msig,pro ...