[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: Display font samples on a computer in C#


This is a slightly improved version of the example List installed fonts on your system in C#. Like the previous example, this version displays font samples. It also lets you set the font's bold, italic, underline, and strikeout properties. It also uses a different method for displaying font samples so it can display combinations that the previous example cannot.

The program executes the following code when it starts.

// List the installed fonts. private void Form1_Load(object sender, EventArgs e) { InstalledFontCollection fonts = new InstalledFontCollection(); foreach (FontFamily font_family in fonts.Families) { lstFonts.Items.Add(font_family.Name); } // Select the first font. lstFonts.SelectedIndex = 0; }

This event handler creates an InstalledFontCollection object. It loops over this object's Families collection and adds the names of the fonts to a ListBox.

When you select a font from the list or check or uncheck any of the check boxes, the program calls the following code to display a sample of the selected font.

// Display a sample of the selected font. private void ShowSample() { // Compose the font style. FontStyle font_style = FontStyle.Regular; if (chkBold.Checked) font_style |= FontStyle.Bold; if (chkItalic.Checked) font_style |= FontStyle.Italic; if (chkUnderline.Checked) font_style |= FontStyle.Underline; if (chkStrikeout.Checked) font_style |= FontStyle.Strikeout; // Get the font size. float font_size = 8; try { font_size = float.Parse(txtSize.Text); } catch { } // Get the font family name. string family_name = "Times New Roman"; if (!(lstFonts.SelectedItem == null)) family_name = lstFonts.SelectedItem.ToString(); // Set the sample's font. txtSample.Font = new Font(family_name, font_size, font_style); }

This method creates a FontStyle enumerated variable to represent the selected font style and parses the desired font size. It then creates a font and makes the txtSample TextBox use it. Initially the TextBox contains the alphabet in upper and lower case, the digits, and an assortment of special symbols, but you can type into the TextBox to see what other strings look like in the selected font.

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

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