8.1 Find All Installed Fonts


Problem

You need to retrieve a list of all the fonts that are installed on the current computer.

Solution

Create a new instance of the System.Drawing.Text.InstalledFontCollection class, which contains a collection of FontFamily objects representing all the installed fonts.

Discussion

The InstalledFontCollection class allows you to retrieve information about currently installed fonts. The following code shows a form that iterates through the font collection when it's first created. Every time it finds a font, it creates a new label that will display the font name in the given font face (at a size of 14 point). The label is added to a scrollable panel, allowing the user to scroll through the list of available fonts.

 using System; using System.Windows.Forms; using System.Drawing; using System.Drawing.Text; public class ListFonts : System.Windows.Forms.Form {     private System.Windows.Forms.Panel pnlFonts;     // (Designer code omitted.)     private void ListFonts_Load(object sender, System.EventArgs e) {              // Create the font collection.         InstalledFontCollection fontFamilies = new InstalledFontCollection();                      // Iterate through all font families.         int offset = 10;         foreach (FontFamily family in fontFamilies.Families) {                      try {                              // Create a label that will display text in this font.                 Label fontLabel = new Label();                 fontLabel.Text = family.Name;                 fontLabel.Font = new Font(family, 14);                 fontLabel.Left = 10;                 fontLabel.Width = pnlFonts.Width;                 fontLabel.Top = offset;                 // Add the label to a scrollable panel.                 pnlFonts.Controls.Add(fontLabel);                 offset += 30;                         }catch {                              // An error will occur if the selected font does                 // not support normal style (the default used when                 // creating a Font object). This problem can be                 // harmlessly ignored.             }         }     } } 

Figure 8.1 shows a screen shot of this simple test application.


Figure 8.1: A list of installed fonts.



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net