C# - How to use a custom Font without installing it in the system

14,030

Solution 1

If you're still reading this, I might point out that you don't have to use unsafe code to load the font from a resource. Here's an example using Marshal.

PrivateFontCollection _fonts = new PrivateFontCollection();

byte[] fontData = Resources.CustomFontResourceName;

IntPtr fontPtr = Marshal.AllocCoTaskMem(fontData.Length);

Marshal.Copy(fontData, 0, fontPtr, fontData.Length);

_fonts.AddMemoryFont(fontPtr, fontData.Length);

Marshal.FreeCoTaskMem(fontPtr);

Font customFont = new Font(_fonts.Families[0], 6.0F);

Solution 2

Note that if you use AddMemoryFont, you will need to use this api call "AddFontMemResourceEx" or it wont work.

PrivateFontCollection giving me symbols

Share:
14,030
user295744
Author by

user295744

Updated on July 20, 2022

Comments

  • user295744
    user295744 almost 2 years

    Once again I need your help.

    I'm developing a small application on C# that uses a custom Font. The problem is, the font must be installed previously on the system. If the font is not present in the system it just uses Times New Roman. Is there any way to embed the font file in the application so it doesn't need to be installed in every system?

    Thank you.

  • Cody Gray
    Cody Gray over 13 years
    The article that the accepted answer links to explains that this is an option, both for VB.NET programmers and for those who don't want to use unsafe in C#.
  • Shibumi
    Shibumi over 13 years
    @Cody Then, I suppose, here is an example :).
  • fireydude
    fireydude almost 11 years
    when I use this approach to load fonts on my development machine it only works with .ttf fonts and not with .otf fonts. When I deploy my website to the cloud (windows azure) it only works with .otf fonts and not with .ttf fonts. How can this be?
  • Shibumi
    Shibumi almost 11 years
    December 2010 was a long time ago! My only guess would be different .NET versions/flavors/configurations? Different OS settings? I think you might just have another question, rather than a comment to this one :). Good luck!