Skip to content

Instantly share code, notes, and snippets.

@lomedil
Last active August 29, 2015 14:08
Show Gist options
  • Save lomedil/815d29c43177b8be5ed7 to your computer and use it in GitHub Desktop.
Save lomedil/815d29c43177b8be5ed7 to your computer and use it in GitHub Desktop.
How to use embedded fonts in Winforms
public class partial FooForm : System.Windows.Forms.Form
{
public FooForm()
{
_privateFonts = Utils.GetEmbeddedFont(Resources.FontAwesome);
}
private PrivateFontCollection _privateFonts;
}
public static class Utils
{
[DllImport("gdi32.dll")]
public static extern IntPtr AddFontMemResourceEx(
IntPtr pbFont,
uint cbFont,
IntPtr pdv,
[System.Runtime.InteropServices.In] ref uint pcFonts);
public static PrivateFontCollection GetEmbeddedFont(byte[] fontBytes)
{
var fonts = new PrivateFontCollection();
byte[] fontData = Properties.Resources.FontAwesome;
IntPtr fontPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(fontData.Length);
System.Runtime.InteropServices.Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
uint dummy = 0;
fonts.AddMemoryFont(fontPtr, Properties.Resources.FontAwesome.Length);
Win32.AddFontMemResourceEx(fontPtr, (uint)Properties.Resources.FontAwesome.Length, IntPtr.Zero, ref dummy);
System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);
return fonts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment