2013-04-09 69 views
1

我可以提高我的功能,不按每个元素搜索?字体已安装?功能

#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 

UPDATE:

好吧,现在我看到了 “.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 

我有同样的问题:是最好的通过第二种方式改进,还是我可以改进得更好?

回答

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 
+0

谢谢,但我有两个小问题:第一:最终使用后返回值是否有效?我的意思是,如果“TestFont”真的在“return”之后结束/关闭,第二:你的方式不要比较每个元素? (对不起,如果这是一个愚蠢的问题) – ElektroStudios 2013-04-09 09:30:16

+0

你只想检查字体是否安装,永远不会有两个同名的字体,使用它的最终结果仍然会清理内存中的对象 – 2013-04-09 09:35:13

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将显示适当的字体。

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