可能重复:
测试是否安装了字体
假设我在系统上使用安装的字体:
new System.Drawing.Font("Arial", 120F);
一切都很好。现在,如果我使用不存在的字体:
new System.Drawing.Font("IdoNotExistHaHa", 120F);
我没有任何例外。如我所见,如果我使用不存在的字体,我会得到标准字体(arial?,不确定)。无论如何,如果找不到字体,我想抛出异常。如何?
MSDN says as following :
For more information about how to construct fonts, see How to: Construct Font Families and Fonts. Windows Forms applications support TrueType fonts and have limited support for OpenType fonts. If you attempt to use a font that is not supported, or the font is not installed on the machine that is running the application, the Microsoft Sans Serif font will be substituted.
You can check the if the font is correct by doing as following :
var myFont = new Font(fontName)
if (myFont.Name != fontName )
{
throw new Exception()
}
您可以在文档本身中看到它,Font Constructor (String, Single)
Windows 窗体应用程序支持 TrueType 字体,但对 OpenType 字体的支持有限。如果 familyName 参数指定的字体未安装在运行应用程序的机器上或不受支持,则将替换为 Microsoft Sans Serif。
简而言之,默认字体是Microsoft Sans Serif
You could check and see if the font is installed first. From Jeff Hillman's answer here: Test if a Font is installed
string fontName = "Consolas";
float fontSize = 12;
Font fontTester = new Font(
fontName,
fontSize,
FontStyle.Regular,
GraphicsUnit.Pixel );
if ( fontTester.Name == fontName )
{
// Font exists
}
else
{
// Font doesn't exist
}
Obviously, you could then throw an exception if you wanted(as that is your original question), although I would recommend not to, throwing an exception is an expensive operation if you can handle the issue more gracefully without.