TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Font Type

This C# program uses the Font type. It requires Windows Forms.

Font. The Font type represents a typeface.

It is found in the .NET Framework—and used in C# programs. We create an instance of the Font type with its constructor. We then use the reference returned to specify typefaces.

Constructor. This example is a Windows Forms program and its uses the simplest Font constructor. We specify a font name ("Times New Roman") as the first argument. The second argument is of type float and specifies the size.

Tip: If you get an error about the number format of the second argument, use the "f" suffix to specify that the number should be a float.

Suffixes

Example that creates Font instance: C#

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
	    Font font = new Font("Times New Roman", 12.0f);

	    // Set Font property and then add a new Label.
	    this.Font = font;
	    this.Controls.Add(new Label() { Text = "Dot Net Perls" });
	    this.Size = new Size(300, 200);
	}
    }
}

The result of the above program is shown in the screenshot. A new label that inherits the Font created in the program is shown. The well-known Times New Roman type face is used to render the text.

FontStyle, FontFamily. Next we demonstrate a more complex constructor. We introduce the FontFamily type. This type describes a specific family of fonts, such as the "Times New Roman" family. No style, size, or other information is part of the FontFamily.

In the Font constructor, we specify the FontStyle using the bitwise OR operator. This is used on enums with the [Flags] attribute. The program renders a Label with "Times New Roman" that is bold, italic, and underlined at 16 points.

Enum Flags Attribute

Example that uses another Font constructor: C#

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
	    FontFamily family = new FontFamily("Times New Roman");

	    Font font = new Font(family, 16.0f,
		FontStyle.Bold | FontStyle.Italic | FontStyle.Underline);

	    // Set Font property.
	    this.Font = font;
	    this.Controls.Add(new Label() { Text = "Dot Net Perls", Width = 250 });
	    this.Size = new Size(300, 200);
	}
    }
}

Bold, Italic, Underline. The Font type also provides the properties Bold, Italic, and Underline. These properties are read-only. You can access them to determine the styles set on the Font, but can't change the styles. You must instead use the Font constructor.

Font.Style. The Style property on the Font type is also read-only. It will tell you what styles are set on the Font instance, but you cannot mutate them. Instead, you can create a new Font with the constructor.

FontFamily represents families of fonts separately from their styles. This means that if you use the font "Times New Roman" in several different sizes and styles in your program, you only need one FontFamily instance for all of them.

Note: This can reduce bugs caused by trying to store all the family information in strings.

Font exists. Some fonts don't exist on some systems. We develop code that chooses the best font for a program. Windows Vista and Office 2007 offer many fonts. But if your program simply sets these as the font, older systems will show a default font.

Tip: Windows Forms has an interesting behavior with the Font object when the font doesn't exist on the system.

And: It will simply not create the new font at all. Thus you can check whether that happened to see if the font exists.

C# program that uses Font objects

public partial class Form1 : Form
{
    public Form1()
    {
	SetFontFinal();
	InitializeComponent();
    }

    private void SetFontFinal()
    {
	string fontName = "Cambria";
	Font testFont = new Font(fontName, 16.0f, FontStyle.Regular,
				 GraphicsUnit.Pixel);

	if (testFont.Name == fontName)
	{
	    // The font exists, so use it.
	    this.Font = testFont;
	}
	else
	{
	    // The font we tested doesn't exist, so fallback to Times.
	    this.Font = new Font("Times New Roman", 16.0f,
				 FontStyle.Regular, GraphicsUnit.Pixel);
	}
    }
}

In this example, the SetFontFinal method is called. This custom method encapsulates the logic for the font existence testing. The font is "Cambria," which is only present on recent versions of windows.

After we make the new Font object, we can test the Name property on it. If the name "Cambria" is still set, the font exists. If the Name property is not the same as specified, the font doesn't exist. In this case we another font.

Tip: It is possible to programmatically choose the best font. This also allows you to set different sizes on the various alternative fonts.

Summary. The Font type is useful in graphical programs in the .NET Framework and C# language. It cannot represent colors of fonts, but it does store information about styles, sizes and type faces.

Also: You can combine the Font type with a FontFamily instance that helps separate parts of your Font requirements.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf