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

时间:2014-08-07 12:38:59   收藏:0   阅读:290

  实例化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类

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,遭遇字体不存在的情况。,布布扣,bubuko.com

评论(0)
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!