[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.