C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
SuffixesExample 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 = "The Dev Codes" });
this.Size = new Size(300, 200);
}
}
}
Info: In the Font constructor, we specify the FontStyle using the bitwise OR operator. This is used on enums with the [Flags] attribute.
Result: The program renders a Label with "Times New Roman" that is bold, italic, and underlined at 16 points.
Enum FlagsExample 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 = "The Dev Codes", Width = 250 });
this.Size = new Size(300, 200);
}
}
}
Note: This can reduce bugs caused by trying to store all the family information in strings.
And: It will simply not create the new font at all. Thus you can check whether that happened to see if the font exists.
SetFontFinal: This method uses logic for font existence testing. The font is "Cambria," which is only present on recent versions of windows.
Name: 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.
But: If the Name property is not the same as specified, the font doesn't exist. In this case we another font.
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);
}
}
}