How to make sure the font exists before using it with .NET.

I have a VB.NET Windows Forms project that at some point draws text directly onto the form at runtime. Before writing a font, I want to make sure that the font and font size exist on the user machine. If they do not, I will try a few more similar fonts, ultimately with Arial by default or something like that.

What is the best way to test and verify the font on a user's computer?

+2
source share
4 answers

From an MSDN article entitled "How To: Enumerate Installed Fonts", I found this code:

InstalledFontCollection installedFontCollection = new InstalledFontCollection(); // Get the array of FontFamily objects. FontFamily[] fontFamilies = installedFontCollection.Families; 
+8
source

Here is one solution: C #:

 public partial class Form1 : Form { public Form1() { SetFontFinal(); InitializeComponent(); } /// <summary> /// This method attempts to set the font in the form to Cambria, which /// will only work in some scenarios. If Cambria is not available, it will /// fall back to Times New Roman, so the font is good on almost all systems. /// </summary> 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); } } } 

And here is one method in VB:

 Public Function FontExists(FontName As String) As Boolean Dim oFont As New StdFont Dim bAns As Boolean oFont.Name = FontName bAns = StrComp(FontName, oFont.Name, vbTextCompare) = 0 FontExists = bAns End Function 
+2
source

See also this same question that leads to this code:

  private bool IsFontInstalled(string fontName) { using (var testFont = new Font(fontName, 8)) { return 0 == string.Compare( fontName, testFont.Name, StringComparison.InvariantCultureIgnoreCase); } } 
+1
source

Arial Bold Italic is unlikely to be a font. This is a subclass of the Arial family.

Try to make it simple and check for "Arial".

0
source

All Articles