Wednesday, February 5, 2014

How to have custom font?

using System.Drawing;
using System.Runtime.InteropServices;

namespace Form1
{
    public partial class Form1 : Form
    {
        //Add Font
        [DllImport("gdi32.dll")]
        private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont,
          IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);

        FontFamily ff;
        Font font;
    }

        private void Form1_Load(object sender, EventArgs e)
        {
              LoadFont();
              this.Font = new Font(ff, 15f, FontStyle.Regular);
        }

        private void LoadFont()
        {
            try
            {
                byte[] fontArray = GPnL.Properties.Resources.helveticaneuewebfont;
                int dataLength = GPnL.Properties.Resources.helveticaneuewebfont.Length;

                IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);

                Marshal.Copy(fontArray, 0, ptrData, dataLength);

                uint cFonts = 0;

                AddFontMemResourceEx(ptrData, (uint)fontArray.Length, IntPtr.Zero, ref cFonts);

                PrivateFontCollection pfc = new PrivateFontCollection();

                pfc.AddMemoryFont(ptrData, dataLength);

                Marshal.FreeCoTaskMem(ptrData);
                ff = pfc.Families[0];

                font = new Font(ff, 15f, FontStyle.Regular);
            }
            catch (Exception e)
            {
                MessageBox.Show(this, "loadFont" + e.Message, "Exception");
            }
        }

No comments:

Post a Comment