zoukankan      html  css  js  c++  java
  • 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_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionFonts",
                        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

  • 相关阅读:
    非常优秀的iphone学习文章总结!
    转载:开源一款酷跑游戏源码完整版
    Faiss学习:一
    揭开Faiss的面纱 探究Facebook相似性搜索工具的原理
    集成学习总结 & Stacking方法详解
    转:fastText原理及实践(达观数据王江)
    转:ubuntu 下GPU版的 tensorflow / keras的环境搭建
    转:PCA的Python实现
    2017知乎看山杯总结(多标签文本分类)
    转:TensorFlow入门(六) 双端 LSTM 实现序列标注(分词)
  • 原文地址:https://www.cnblogs.com/geovindu/p/7463728.html
Copyright © 2011-2022 走看看