是否有一种简单的方法(在.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 fontFamily in fontsCollection.Families) { if (fontFamily.Name == fontName) {...} \\ check if font is 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; }