Using custom fonts on a Label on Winforms

After looking through possibly 30-50 posts on this, I have finally been able to come up with a solution that actually works!
Please follow the steps sequentially:

1.) Include your font file (in my case, ttf file) in your application resources. To do this, double-click on the “Resources.resx” file.

enter image description here

2.) Highlight the “Add resource” option and click the down-arrow. Select “Add existing file” option. Now, search out your font file, select it, and click OK. Save the “Resources.resx” file.

enter image description here

3.) Create a function (say, InitCustomLabelFont() ), and add the following code in it.

        //Create your private font collection object.
        PrivateFontCollection pfc = new PrivateFontCollection();

        //Select your font from the resources.
        //My font here is "Digireu.ttf"
        int fontLength = Properties.Resources.Digireu.Length;

        // create a buffer to read in to
        byte[] fontdata = Properties.Resources.Digireu;

        // create an unsafe memory block for the font data
        System.IntPtr data = Marshal.AllocCoTaskMem(fontLength);

        // copy the bytes to the unsafe memory block
        Marshal.Copy(fontdata, 0, data, fontLength);

        // pass the font to the font collection
        pfc.AddMemoryFont(data, fontLength);

Your custom font has now been added to the PrivateFontCollection.

4.) Next, assign the font to your Label, and add some default text into it.

        //After that we can create font and assign font to label
        label1.Font = new Font(pfc.Families[0], label1.Font.Size);
        label1.Text = "My new font";

5.) Go to your form layout and select your label. Right-click it and select “Properties“. Look for the property “UseCompatibleTextRendering” and set it to “True“.

6.) If necessary you can release the font after you are sure that it can never be used again. Call the PrivateFontCollection.Dispose() method, you can then also call Marshal.FreeCoTaskMem(data) safely. It is pretty common to not bother and leave the font loaded for the life of the app.

7.) Run your application. You shall now see that you custom font has been set for the given label.

Cheers!

Leave a Comment