首页 > 代码库 > C# 安装字体

C# 安装字体

遍历所有字体

InstalledFontCollection MyFont = new InstalledFontCollection();FontFamily[] MyFontFamilies = MyFont.Families;List<string> installedFontNames = new List<string>();int Count = MyFontFamilies.Length;for (int i = 0; i < Count; i++){    string FontName = MyFontFamilies[i].Name;    installedFontNames.Add(FontName);}string fontDir = Application.StartupPath + "\\Fonts";if (Directory.Exists(fontDir)){    string[] fontFiles = Directory.GetFiles(fontDir);    foreach (string fontFile in fontFiles)    {        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fontFile);        if (!installedFontNames.Contains(fileNameWithoutExtension))        {        }    }}

 

安装字体

[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 fontPath){    string fontFileName = Path.GetFileName(fontPath);    string fontNameWithoutExtenstion = Path.GetFileNameWithoutExtension(fontPath);    string WinFontDir = Environment.GetEnvironmentVariable("WINDIR") + "\\fonts";    string FontPath = WinFontDir + "\\" + fontFileName;    if (!File.Exists(FontPath))    {        File.Copy(fontPath, FontPath);        AddFontResource(FontPath);        WriteProfileString("fonts", fontNameWithoutExtenstion + "(TrueType)", fontFileName);    }}

 临时字体

public static Font CreateFont(string fontName, float height, FontStyle fontStyle = FontStyle.Bold){    Font font;    if (File.Exists(Application.StartupPath + "\\Fonts\\" + fontName + ".ttf"))    {        PrivateFontCollection privateFonts = new PrivateFontCollection();        privateFonts.AddFontFile(Application.StartupPath + "\\Fonts\\" + fontName + ".ttf");        font = new Font(privateFonts.Families[0], height, fontStyle);    }    else    {        font = new Font(fontName, height);    }    return font;}

 内存字体

public static Font CreateFont(Setting setting){    setting.FontFamily = setting.FontFamily ?? "";    PrivateFontCollection p_Font = new PrivateFontCollection();    var o = Properties.Resources.ResourceManager.GetObject(setting.FontFamily);    if (o is byte[])    {        byte[] b_Font = o as byte[];        IntPtr MeAdd = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * b_Font.Length);        Marshal.Copy(b_Font, 0, MeAdd, b_Font.Length);        p_Font.AddMemoryFont(MeAdd, b_Font.Length);        return new Font(p_Font.Families[0], 14.25F, FontStyle.Bold);    }    return new Font("宋体", 14.25f, FontStyle.Bold);}