字体已安装?功能

时间:2013-04-09 09:13:48

标签: vb.net visual-studio visual-studio-2012 fonts font-family

我可以改进我的功能,不按每个元素搜索?

#Region " Font Is Installed? Function "

    ' [ Font Is Installed? Function ]
    '
    ' Examples :
    ' MsgBox(Font_Is_Installed("Lucida Console"))

    Private Function Font_Is_Installed(ByVal FontName As String) As Boolean
        Dim AllFonts As New Drawing.Text.InstalledFontCollection
        For Each Font As FontFamily In AllFonts.Families
            If Font.Name.ToLower = FontName.ToLower Then Return True
        Next
        Return False
    End Function

#End Region
  

更新:

好了,现在我看到了“.tolist”功能,现在我的代码是这样的:

Private Function Font_Is_Installed(ByVal FontName As String) As Boolean
    Dim AllFonts As New Drawing.Text.InstalledFontCollection
    Dim FontFamily As New FontFamily(FontName)
    If AllFonts.Families.ToList().Contains(FontFamily) Then Return True Else Return False
End Function

我有同样的问题:第二种方式最好改进,或者我可以更好地改进它?

3 个答案:

答案 0 :(得分:4)

这里是

    Public Shared Function IsFontInstalled(ByVal FontName As String) As Boolean
        Using TestFont As Font = New Font(FontName, 10)
            Return CBool(String.Compare(FontName, TestFont.Name, StringComparison.InvariantCultureIgnoreCase) = 0)
        End Using
    End Function

答案 1 :(得分:3)

    Dim SomeTextBox As TextBox = New TextBox()
    Dim SomeFontFamily As FontFamily = Nothing
    Dim SomeFontCollection As PrivateFontCollection = Nothing

    Try
        SomeFontFamily = New FontFamily("SomeFontFamilyName")
    Catch ex As Exception
        SomeFontCollection = New PrivateFontCollection()
        SomeFontCollection.AddFontFile("SomeFontFileName")
        SomeFontFamily = SomeFontCollection.Families(0)
    End Try

    SomeTextBox.Font = New Font(SomeFontFamily, 12)

这样,如果无法从本地字体创建SomeFontFamily,则只能从文件创建它。 SomeTextBox将显示正确的字体。

答案 2 :(得分:1)

这是一个例子。只需尝试分配字体名称,如果它生成错误,请捕获它并返回false。

Private Function isFontInstalled(ByVal FontName As String) As Boolean
    Try
        Dim FontFamily As New FontFamily(FontName)
        FontFamily.Dispose()
        Return True
    Catch
        Return False
    End Try
End Function
相关问题