A set of .NET Framework managed libraries for developing graphical user interfaces.
Hello @mc ,
Thanks for your question.
Simply copying the font file into the C:\Windows\Fonts folder is not enough to make it available to your application. Windows needs to properly register the font. On servers (especially Windows Server 2022), this often doesn't happen reliably.
I recommend using PrivateFontCollection, which loads the font directly from the file.
- Add the font file to your project:
- Create a folder called
Fontsin your WinForms project. - Copy your
.ttf(or.otf) file into this folder. - In Solution Explorer, right-click the font file → Properties → Set Copy to Output Directory to Copy if newer.
- Find the correct font family name:
- Double-click your font file on your computer.
- In the preview window, look at the big name at the top.
- You can also check the
Detailstab in fileProperties.
- You can refer to following example code:
using System.Drawing;
using System.Drawing.Text;
using System.IO;
public partial class YourForm : Form
{
private PrivateFontCollection privateFonts = new PrivateFontCollection();
public YourForm()
{
InitializeComponent();
LoadCustomFont();
}
private void LoadCustomFont()
{
try
{
string fontPath = Path.Combine(Application.StartupPath, "Fonts", "MyCustomFont.ttf");
if (File.Exists(fontPath))
{
privateFonts.AddFontFile(fontPath);
}
else
{
MessageBox.Show("Font file not found!");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to load font: " + ex.Message);
}
}
private void ApplyCustomFont(Control control, float size = 12f, FontStyle style = FontStyle.Regular)
{
if (privateFonts.Families.Length > 0)
{
FontFamily family = privateFonts.Families[0];
control.Font = new Font(family, size, style);
}
}
private void Form_Load(object sender, EventArgs e)
{
ApplyCustomFont(label1, 14f);
ApplyCustomFont(button1, 12f);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
privateFonts?.Dispose();
}
base.Dispose(disposing);
}
}
Note: please replace "MyCustomFont.ttf" with your actual filename.
I hope this addresses your question. If this response was helpful, please consider following the guidance to provide feedback.