[.NET源码学习]实例化Font,遭遇字体不存在的情况。

时间:2021-11-11 21:08:25

  实例化Font类时,当传入参数为不存在或未安装的字体时,Windows系统会用Microsoft Sans Serif字体替代该字体。

  Msdn:

    "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."

  

  情景

    利用 New Font("字体",.....) ,当该字体不存在时,我本以为会用系统默认的输入法代替之,后来查看了MSDN,发现事实似乎并非如此。决定查找一下源代码。

  

  源码

   System.Drawing.Font类

 private void Initialize(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
this.originalFontName = familyName;
this.SetFontFamily(new FontFamily(Font.StripVerticalName(familyName), true));
this.Initialize(this.fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}

System.Drawing.FontFamily类

 internal FontFamily(string name, bool createDefaultOnFail)
{
this.createDefaultOnFail = createDefaultOnFail;
this.CreateFontFamily(name, null);
}
 private void CreateFontFamily(string name, FontCollection fontCollection)
{
IntPtr intPtr = IntPtr.Zero;
IntPtr handle = (fontCollection == null) ? IntPtr.Zero : fontCollection.nativeFontCollection;
int num = SafeNativeMethods.Gdip.GdipCreateFontFamilyFromName(name, new HandleRef(fontCollection, handle), out intPtr);
if (num != )
{
if (this.createDefaultOnFail)
{
intPtr = FontFamily.GetGdipGenericSansSerif();
}
else
{
if (num == )
{
throw new ArgumentException(SR.GetString("GdiplusFontFamilyNotFound", new object[]
{
name
}));
}
if (num == )
{
throw new ArgumentException(SR.GetString("GdiplusNotTrueTypeFont", new object[]
{
name
}));
}
throw SafeNativeMethods.Gdip.StatusException(num);
}
}
this.SetNativeFamily(intPtr);
}
 private static IntPtr GetGdipGenericSansSerif()
{
IntPtr zero = IntPtr.Zero;
int num = SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif(out zero);
if (num != )
{
throw SafeNativeMethods.Gdip.StatusException(num);
}
return zero;
}
结论:
【SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif】方法,Windows系统下返回Microsoft Sans Serif字体。 由此可见,当实例化字体不存在时,Windows下固定返回Microsoft Sans Serif字体,与系统默认字体无关。