开发者

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

开发者 https://www.devze.com 2023-01-30 19:02 出处:网络
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.

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

精彩评论

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

关注公众号