標籤:des style blog color art for
遍曆所有字型
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);}