博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Installing Fonts programatically C#
阅读量:5082 次
发布时间:2019-06-13

本文共 10037 字,大约阅读时间需要 33 分钟。

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{    ///     ///     ///     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);        ///         ///         ///         ///         ///         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);        ///         /// 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 没有权限 涂聚文注        ///         /// Your font to be passed as a resource (i.e. "myfont.tff")        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());            }        }        ///         ///         ///         ///         ///         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);        }        ///         ///         ///         ///         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);        }        ///         ///         ///         public Form4()        {            InitializeComponent();        }        ///         ///         ///         ///         ///         private void Form4_Load(object sender, EventArgs e)        {        }        ///         ///         ///         ///         ///         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());            }        }        ///         ///         ///         ///         ///         private void button2_Click(object sender, EventArgs e)        {            FontFamily[] fontList = new System.Drawing.Text.InstalledFontCollection().Families;            InstalledFontCollection installedFonts = new InstalledFontCollection();            List
list = new List
(); 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"; } ///
/// /// ///
///
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; } } } ///
/// /// 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    {        ///         /// 应用程序的主入口点。        ///         [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

转载于:https://www.cnblogs.com/geovindu/p/7463728.html

你可能感兴趣的文章
Json格式的字符串转换为正常显示的日期格式
查看>>
[转]使用 Razor 进行递归操作
查看>>
[转]Android xxx is not translated in yyy, zzz 的解决方法
查看>>
docker入门
查看>>
Android系统--输入系统(十一)Reader线程_简单处理
查看>>
监督学习模型分类 生成模型vs判别模型 概率模型vs非概率模型 参数模型vs非参数模型...
查看>>
Mobiscroll脚本破解,去除Trial和注册时间限制【转】
查看>>
实验五 Java网络编程及安全
查看>>
32位与64位 兼容编程
查看>>
iframe父子页面通信
查看>>
ambari 大数据安装利器
查看>>
java 上传图片压缩图片
查看>>
magento 自定义订单前缀或订单起始编号
查看>>
ACM_拼接数字
查看>>
计算机基础作业1
查看>>
Ubuntu 深度炼丹环境配置
查看>>
C#中集合ArrayList与Hashtable的使用
查看>>
从一个标准 url 里取出文件的扩展名
查看>>
map基本用法
查看>>
poj-1163 动态规划
查看>>