List installed fonts on your system in C#

This example shows how to list installed fonts on a computer. When it starts, the program uses the following code to fill a ListBox with the names of the font families available on the system.

// List the available fonts.
private void Form1_Load(object sender, EventArgs e)
{
    // List the font families.
    InstalledFontCollection installedFonts = new InstalledFontCollection();
    foreach (FontFamily fontFamily in installedFonts.Families)
    {
        lstFonts.Items.Add(fontFamily.Name);
    }

    // Select the first font.
    lstFonts.SelectedIndex = 0;
}

When the user selects a font from the list, the following code displays a sample of it.

// Display a sample of the selected font.
private void lstFonts_SelectedIndexChanged(object sender, EventArgs e)
{
    // Display the font family's name.
    lblSample.Text = lstFonts.Text;

    // Use the font family.
    Font font = MakeFont(lstFonts.Text, 20, FontStyle.Regular);
    if (font == null) font = MakeFont(lstFonts.Text, 20, FontStyle.Bold);
    if (font == null) font = MakeFont(lstFonts.Text, 20, FontStyle.Italic);
    if (font == null) font = MakeFont(lstFonts.Text, 20, FontStyle.Strikeout);
    if (font == null) font = MakeFont(lstFonts.Text, 20, FontStyle.Underline);

    if (font != null) lblSample.Font = font;
}

This code gets the name of the selected font family. It then calls the MakeFont function described shortly to create a 20 point regular font with that name. If MakeFont fails to create the font, the program tries again with different font styles. (On my system, the Aharoni font is available only in bold style not in regular.)

The following code shows the MakeFont method

// Make a font with the given family name, size, and style.
private Font MakeFont(string family, float size, FontStyle style)
{
    try
    {
        return new Font(family, size, style);
    }
    catch
    {
        return null;
    }
}

This code tries to create the desired font. If it fails, it returns null.






This entry was posted in fonts, graphics, system and tagged , , , , , , , , , , . Bookmark the permalink.

One Response to List installed fonts on your system in C#

  1. Pingback: Display font samples on a computer in C# |

Leave a Reply

Your email address will not be published. Required fields are marked *