0

I'm using this code and works fine

Imports System.Drawing.Text

Dim fontInstalled As Boolean = False
Dim fontToSearch As String
Dim fonts As New InstalledFontCollection

fontToSearch = "Verdana"

For Each one As FontFamily In fonts.Families
        'If I want to show every installed family name
        'MsgBox(one.Name)
        If one.Name = fontToSearch Then
            fontInstalled = True
            MsgBox("Font " & fontToSearch & " IS installed!!!")
            Exit For
        End If
    Next

If fontInstalled = False Then MsgBox("Font " & fontToSearch & " is NOT installed")

But I'm sure there will be a cleaner solution using InstalledFontCollection or something but I can't adapt this code to VB.NET Test if a Font is installed

var fontsCollection = new InstalledFontCollection();
foreach (var fontFamiliy in fontsCollection.Families)
{
if (fontFamiliy.Name == fontName) ... \\ installed
}
Community
  • 1
  • 1
fedeteka
  • 943
  • 1
  • 14
  • 33

2 Answers2

3

Whenever you use the keyword New , check to see if it includes a Dispose method. If it does, it means that it likely allocates some resource which needs to be Disposed. So, use it in a Using block

1. Check if installed

Dim IsInstalled As Boolean

Using fnts As New InstalledFontCollection()
    IsInstalled = fnts.Families.
                AsEnumerable().
                Select(Function(s) s.Name).
                Contains("Verdana")
End Using

2. Try It

Using fnt As New Font("Verdana", 12)
    IsInstalled = (fnt IsNot Nothing)
End Using

3. Get List of Installed Names

Dim fontNames As String()
Using fnts As New InstalledFontCollection()
    fontNames = fnts.Families.
                AsEnumerable().
                Select(Function(s) s.Name).
                ToArray()
End Using

Bonus Tip

MsgBox / MessageBox is a horrible way to debug. From the menu select Debug | Windows | Output. You can dock this where ever you want and set it to "Auto Hide" so it hides unless the mouse is over it. To output to it:

For Each s As String In fontNames
    Console.WriteLine(s)
Next

et voila no more clicking to dispose of 172 font name dialogs.

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
  • Worked fine thanks. Also your answer is a complete tutorial with tips. I still have vices of misuse of old Visual Basic. Thanks again. – fedeteka Sep 17 '16 at 11:21
1

A check like this may help:

imports system.drawing.text
...
Function IsFontInstalled(FontName As String) As Boolean
    Dim fonts As New InstalledFontCollection
    For Each one As FontFamily In fonts.Families
        If one.Name = FontName Then
            Return True
        End If
    Next
    Return False
End Function

Ran across this technique:

Function IsFontInstalled(FontName As String) As Boolean

    Using fnt As New Font(FontName, 12)
        Return (fnt IsNot Nothing)
    End Using

End Function

So short you could use the technique in line.

rheitzman
  • 2,247
  • 3
  • 20
  • 36