List the fonts installed on your system in C#

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. The MakeFont function described shortly returns a font with the indicated name, size, and style, or null if it cannot create the font. The several calls to MakeFont were required because on my system the Aharoni font is available only in bold style not in regular (or the others).

// 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;
}

The following code shows the MakeFont function. It simply creates the font, catching the error if there is one.

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

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.