Start New Discussion within our Software Development Community

Hello,

I am struggling at trying to get custom fonts working in my application.

I have added the font file to the project's resources via the 'Add Existing File...' option, and setup the following code...

    FontFamily standard;
    Font wt;
    [DllImport("gdi32.dll", ExactSpelling = true)]
    private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts);

    private Font getWetDreamsFont()
    {
        byte[] theFont = Properties.Resources.Wet_Dreamz_Medium;
        int length = Properties.Resources.Wet_Dreamz_Medium.Length;
        IntPtr ptrData = Marshal.AllocCoTaskMem(length);
        Marshal.Copy(theFont, 0, ptrData, length);
        uint cFonts = 0;
        AddFontMemResourceEx(ptrData, (uint)theFont.Length, IntPtr.Zero, ref cFonts);
        PrivateFontCollection pfc = new PrivateFontCollection();
        pfc.AddMemoryFont(ptrData, length);
        Marshal.FreeCoTaskMem(ptrData);
        standard = pfc.Families[0];
        wt = new Font(standard, 16f, FontStyle.Regular);
        return wt;
    }

Used like so;

e.Graphics.DrawString(capFirst(title), getWetDreamsFont(), Brushes.White, new Point(this.Width / 2 - (getStringWidth(title) / 2), 3));

Everything works if I remove the font function, and change the call to the standard Arial call;

new Font("Arial", 16)

Instead of getting my application drawn, I get a red X and surrounding white box;
http://gyazo.com/20490e494bb8efb8778ef9dc1ed71efc

Help is much appreciated,
Thanks!

Have you placed a break point at the start of that code and stepped through it? You may find that one line doesn't do what it's meant to and knowing exactly what line is causing the issue will help.

This article has been dead for over six months. Start a new discussion instead.