Original Post
Hello all. I've been struggling to get embedded font resources to wokr inside of my C# applications. If the font is loaded from a file outside of my assembly, it works fine and displays inside the application. If I, however, embed the font as a resouce it will not display in run-time. The default font is displayed. There is also other strange behaviour associated with this. If I double-click the font and am viewing it in the font viewer, and THEN I launch my application the font will be displayed in the application like it should. Has anyone else expereinced thins kind of problem? It's not a big deal if I had to install my font on a the user's machine. And it's not that big of a deal if I were to use the font as an external resource. But I really wanted to keep my application in as few files as possible by embedding most of my resources. Here's the code I use to pull font files from my embedded resources. It's late so I'm sorry if there is any bad grammar/typos. EDIT: Another interesting tidbit: If I override my Form's OnPaint method and use Graphics.DrawString() the font is displayed correctly but if the font is used on a label or component it is draw as the default font. Intly when it is explicitly called through Graphics.DrawString() does it show up correctly...
public static PrivateFontCollection GetEmbeddedFonts()
{
PrivateFontCollection fontCollection = new PrivateFontCollection();
Assembly asm = Assembly.GetCallingAssembly();
string[] embeddedResources = asm.GetManifestResourceNames();
foreach(string resourceName in embeddedResources)
{
if(resourceName.ToLower().EndsWith("ttf"))
{
Stream fontStream = asm.GetManifestResourceStream(resourceName);
byte[] buffer = new byte[fontStream.Length];
fontStream.Read(buffer, 0, (int)fontStream.Length);
fontStream.Close();
unsafe
{
fixed (byte* pFontData = buffer)
{
fontCollection.AddMemoryFont((System.IntPtr)pFontData, buffer.Length);
}
}
}
}
return fontCollection;
}