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;The SomethingChanged event handler catches all of the events that influence the font's appearance. This includes:
...
// 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 size TextBox's TextChanged event
- The Bold, Italic, Underline, and Strikeout CheckBoxes' CheckedChanged events
- The font ListBox's SelectedIndexChanged event
private void SomethingChanged(object sender, EventArgs e)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.
{
ShowSample();
}
// 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);
}



Comments