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

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

  Msdn:

    "For more information about how to construct fonts, see How to: Construct Font Families and FontsWindows 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类

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

     System.Drawing.FontFamily类

1 internal FontFamily(string name, bool createDefaultOnFail)
2 {
3     this.createDefaultOnFail = createDefaultOnFail;
4     this.CreateFontFamily(name, null);
5 }
 1 private void CreateFontFamily(string name, FontCollection fontCollection)
 2 {
 3     IntPtr intPtr = IntPtr.Zero;
 4     IntPtr handle = (fontCollection == null) ? IntPtr.Zero : fontCollection.nativeFontCollection;
 5     int num = SafeNativeMethods.Gdip.GdipCreateFontFamilyFromName(name, new HandleRef(fontCollection, handle), out intPtr);
 6     if (num != 0)
 7     {
 8         if (this.createDefaultOnFail)
 9         {
10             intPtr = FontFamily.GetGdipGenericSansSerif();
11         }
12         else
13         {
14             if (num == 14)
15             {
16                 throw new ArgumentException(SR.GetString("GdiplusFontFamilyNotFound", new object[]
17                 {
18                     name
19                 }));
20             }
21             if (num == 16)
22             {
23                 throw new ArgumentException(SR.GetString("GdiplusNotTrueTypeFont", new object[]
24                 {
25                     name
26                 }));
27             }
28             throw SafeNativeMethods.Gdip.StatusException(num);
29         }
30     }
31     this.SetNativeFamily(intPtr);
32 }    
 1 private static IntPtr GetGdipGenericSansSerif()
 2 {
 3     IntPtr zero = IntPtr.Zero;
 4     int num = SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif(out zero);
 5     if (num != 0)
 6     {
 7         throw SafeNativeMethods.Gdip.StatusException(num);
 8     }
 9     return zero;
10 }
结论:
【SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif】方法,Windows系统下返回Microsoft Sans Serif字体。

由此可见,当实例化字体不存在时,Windows下固定返回Microsoft Sans Serif字体,与系统默认字体无关。
            

 

[.NET源码学习]实例化Font,遭遇字体不存在的情况。,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。