开发者

Windows Forms: Can't get font resource to show properly

have added a TrueType font to my project resources ("MyFontResource"), and I've set the build action to "Resource." My intention is to replace the font on a Label object with this resource.

Here's my code:

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

The font displays as expected only when I have the font installed locally. If I haven't installed the font, then I see the font originally assigned to myLabel in my C# project.

Now what?


Never mind, found the reason this doesn't work here.

Here's a solution that works (original code 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜