C# : Using an embedded font on a textbox

时间秒杀一切 提交于 2019-11-30 08:33:35

问题


I'm embedding a font in my app as EmbeddedResource and want to use it in a textbox. AddMemoryFont help says I have to set compatible text rendering to true to use GDI+ so my font can be used, but somehow it just won't display the right font.

in Program.cs I explicitly state : Application.SetCompatibleTextRenderingDefault(true);

So why is it not working ? Anybody got a clue ?


回答1:


Okay, I figured it out thanks to the interwebs and Google.

For future reference, if anybody has this problem, the fix is : after getting your embedded font as a stream, and before calling AddMemoryFont, you have to call AddFontMemResourceEx ! (Not available in C# so you have to import it :

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

and then :

            //create an unsafe memory block for the data
        System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);
        //create a buffer to read in to
        Byte[] fontData = new Byte[fontStream.Length];
        //fetch the font program from the resource
        fontStream.Read(fontData, 0, (int)fontStream.Length);
        //copy the bytes to the unsafe memory block
        Marshal.Copy(fontData, 0, data, (int)fontStream.Length);

        // We HAVE to do this to register the font to the system (Weird .NET bug !)
        uint cFonts = 0;
        AddFontMemResourceEx(data, (uint)fontData.Length, IntPtr.Zero, ref cFonts);

        //pass the font to the font collection
        mFontCollection.AddMemoryFont(data, (int)fontStream.Length);
        //close the resource stream
        fontStream.Close();
        //free the unsafe memory
        Marshal.FreeCoTaskMem(data);

And presto, you'll be able to use the font. Without the AddFontMemResourceEx it wont work.



来源:https://stackoverflow.com/questions/1955629/c-sharp-using-an-embedded-font-on-a-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!