2008-09-22 85 views

回答

23
string fontName = "Consolas"; 
float fontSize = 12; 

using (Font fontTester = new Font( 
     fontName, 
     fontSize, 
     FontStyle.Regular, 
     GraphicsUnit.Pixel)) 
{ 
    if (fontTester.Name == fontName) 
    { 
     // Font exists 
    } 
    else 
    { 
     // Font doesn't exist 
    } 
} 
+6

這隻適用於Regular字體樣式可用 – jltrem 2013-07-11 14:29:38

15

How do you get a list of all the installed fonts?

var fontsCollection = new InstalledFontCollection(); 
foreach (var fontFamiliy in fontsCollection.Families) 
{ 
    if (fontFamiliy.Name == fontName) ... \\ installed 
} 

詳見InstalledFontCollection class

MSDN:
Enumerating Installed Fonts

+3

這是對我來說最「直接」的方式,其他建議的答案看起來更像是解決方法。 – 2012-04-13 07:26:43

+0

@UururTuran:是的,但是我想知道性能?直到你嘗試纔會知道,但是由於有查表的機會,其他人會更快。 – Hans 2013-02-01 19:31:05

12

感謝傑夫,我有更好的閱讀字體類的文檔:

如果familyName參數 指定了未安裝 字體在運行應用程序 或不受支持的計算機上,Microsoft Sans Serif將被替換。

這方面的知識,結果:

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

都會響起GVS」的回答:使用Font創作如果FontStyle.Regular只可提出工作

private static bool IsFontInstalled(string fontName) 
    { 
     using (var testFont = new Font(fontName, 8)) 
      return fontName.Equals(testFont.Name, StringComparison.InvariantCultureIgnoreCase); 
    } 
5

其他的答案。一些字體,例如Verlag Bold,沒有固定的風格。創作失敗,例外字體'Verlag Bold'不支持style'Regular'。您需要檢查應用程序需要的樣式。一個解決辦法如下:

public static bool IsFontInstalled(string fontName) 
    { 
    bool installed = IsFontInstalled(fontName, FontStyle.Regular); 
    if (!installed) { installed = IsFontInstalled(fontName, FontStyle.Bold); } 
    if (!installed) { installed = IsFontInstalled(fontName, FontStyle.Italic); } 

    return installed; 
    } 

    public static bool IsFontInstalled(string fontName, FontStyle style) 
    { 
    bool installed = false; 
    const float emSize = 8.0f; 

    try 
    { 
     using (var testFont = new Font(fontName, emSize, style)) 
     { 
      installed = (0 == string.Compare(fontName, testFont.Name, StringComparison.InvariantCultureIgnoreCase)); 
     } 
    } 
    catch 
    { 
    } 

    return installed; 
    } 
1

這是我會怎麼做:

private static bool IsFontInstalled(string name) 
{ 
    using (InstalledFontCollection fontsCollection = new InstalledFontCollection()) 
    { 
     return fontsCollection.Families 
      .Any(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)); 
    } 
} 

一件事本就是Name財產並不總是你從看用C期待什麼要注意:\ WINDOWS \字體。例如,我安裝了一個名爲「Arabic Typsetting Regular」的字體。 IsFontInstalled("Arabic Typesetting Regular")將返回false,但IsFontInstalled("Arabic Typesetting")將返回true。 (「阿拉伯文排版」是Windows的字體預覽工具中的字體名稱)。

就資源去說吧,我跑了一個測試,在那裏我多次調用這個方法,測試只用了幾個毫秒每次。我的機器有點過於強大,但是除非你需要頻繁地運行這個查詢,否則性能看起來非常好(即使你這樣做了,那就是緩存的用處)。