C# Use/Load custom fonts (WinForms +)

Date: 2021-03-17
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;

public static class FontConfig
{
	private static PrivateFontCollection Collection;

	static FontConfig()
	{
		LoadFonts(new List<string>() {
			@"Quicksand-VariableFont_wght.ttf",
			@"Verdana.ttf"
		});
	}

	private static void LoadFonts(IEnumerable<string> fontFiles)
	{
		Collection = new PrivateFontCollection();
		foreach (var fontFile in fontFiles)
		{
			var fileName = GetRelativePath(fontFile);
			if (!File.Exists(fileName)) continue;
			Collection.AddFontFile(fileName);
		}
	}

	private static string GetRelativePath(string fileName) => Path.Combine(GetExePath(), fileName);
	private static string GetExePath() => Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

	public static Font GetFont(string name, float size, FontStyle fontStyle = FontStyle.Regular)
	{
		var family = new FontFamily(name, Collection);
		return new Font(family, size, fontStyle, GraphicsUnit.Pixel);
	}
	//public static Font ControlFont { get; } = GetFont("Quicksand", 12);
	public static Font ControlFont { get; } = GetFont("Verdana", 12);
}
47050cookie-checkC# Use/Load custom fonts (WinForms +)