2010-12-16 76 views
0

已将TrueType字体添加到我的项目资源(“MyFontResource”)中,并且已将生成操作设置为“Resource”。我的意图是用这个资源替换Label对象上的字体。Windows窗体:无法正确显示字体资源

这里是我的代码:

PrivateFontCollection myFonts = new PrivateFontCollection(); 
unsafe { 
    fixed (byte* fontBytes = Properties.Resources.MyFontResource) 
     myFonts.AddMemoryFont((IntPtr)fontBytes, Properties.Resources.MyFontResource.Length); 
} 
myLabel.Font = new Font(myFonts.Families[0], 10f); 

,因为只有预期时,我有字体本地安装的字体显示。如果我没有安装字体,那么我会在C#项目中看到最初分配给myLabel的字体。

现在呢?

回答

3

没关系,发现原因这不起作用here

这里是一个有效的解决方案(原代码here):

class MyClass { 
    [DllImport("gdi32.dll")] 
    private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts); 

    public MyClass() { 
     uint installCount = 1; 
     PrivateFontCollection myFonts = new PrivateFontCollection(); 
     unsafe { 
      fixed (byte* pFontData = Properties.Resources.MyFont) { 
       myFonts.AddMemoryFont((IntPtr)pFontData, Properties.Resources.MyFont.Length); 
       AddFontMemResourceEx((IntPtr)pFontData, (uint)Properties.Resources.MyFont.Length, IntPtr.Zero, ref installCount); 
      } 
     } 
     myLabel.Font = new Font(myFonts.Families[0], 20f); 
    } 
} 
+0

看起来很熟悉。 – 2010-12-16 21:37:07

+0

谢谢,你的代码让我不必记住VB。 – 2012-05-18 19:04:38