是否有一种简单的方法(在.Net中)来测试当前机器上是否安装了Font?

有帮助吗?

解决方案

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
    }
}

其他提示

你如何得到一个所有已安装字体的列表?

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

有关详细信息,请参阅 InstalledFontCollection类

MSDN:结果 枚举已安装的字体

感谢Jeff,我最好阅读Font类的文档:

  

如果是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);
        }
    }

使用 Font 创建的其他答案仅在 FontStyle.Regular 可用时才有效。某些字体,例如Verlag Bold,没有常规样式。创建将失败,例外 Font'Verlag Bold'不支持样式'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;
  }

关闭GvS的回答:

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

我将如何做到这一点:

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 \ Fonts中查看的内容。例如,我安装了一个名为“Arabic Typsetting Regular”的字体。 IsFontInstalled(" Arabic Typesetting Regular")将返回false,但 IsFontInstalled(" Arabic Typesetting")将返回true。 (“阿拉伯语排版”是Windows'字体预览工具中的字体名称。)

就资源而言,我进行了一次测试,我多次调用此方法,测试每次只需几毫秒。我的机器有点过于强大,但除非你需要非常频繁地运行这个查询,否则性能似乎非常好(即使你这样做,也就是缓存的目的)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top