I am working on a program and I want custom font for labels and buttons I searched a lot to find solution I tried with this code but it works only with Home form if I move the font to another form program working for maybe 5 seconds and stopped.
[DllImport("gdi32.dll")]
public static extern IntPtr AddFontMemResourceEx(IntPtr pbfont, uint cbfont,
IntPtr pdv, [In] ref uint pcFonts);
FontFamily ff;
Font font;
public void AllcoBold(Font f, Control c, float size)
{
FontStyle fs = FontStyle.Bold;
c.Font = new Font(ff, size, fs);
}
public void loadBold()
{
byte[] fontArray = Counter.Properties.Resources.TheSans;
int datalength = Counter.Properties.Resources.TheSans.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.Bold);
}
private void LoadFontStyleBold()
{
AllcoBold(font, startBtn, 14);
}
pfc
should be a class field of typePrivateFontCollection
. Instantiate it inloadBold
method and dispose of it (pfc.Dispose();
) in theFormClosed
event. Get rid of 1)Marshal.FreeCoTaskMem(ptrData);
, this releases the data required to keep the custom Font alive. 2) The class fieldsff
andfont
. You can get them frompfc
. Also, you can writeint datalength = fontArray.Length;
instead.