Display the fonts installed on the computer and show samples of them in C#

When the program loads, it creates an InstalledFontCollection object. It loops over this object's Families collection and adds the names of the fonts to a ListBox.

using System.Drawing.Text;
...
// 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;
}

The SomethingChanged event handler catches all of the events that influence the font's appearance. This includes:

  • The size TextBox's TextChanged event
  • The Bold, Italic, Underline, and Strikeout CheckBoxes' CheckedChanged events
  • The font ListBox's SelectedIndexChanged event

SomethingChange simply calls the ShowSample function to actually display the sample.

private void SomethingChanged(object sender, EventArgs e)
{
ShowSample();
}

Function ShowSample builds the necessary FontStyle, parses the font size, and gets the selected font's name. It then builds the font and makes the sample TextBox use it.

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

   

 

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.