Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

fonts

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.

like image 550
user295744 Avatar asked Dec 10 '10 16:12

user295744


2 Answers

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);
like image 142
Shibumi Avatar answered Nov 09 '22 17:11

Shibumi


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

PrivateFontCollection giving me symbols

like image 43
Will Avatar answered Nov 09 '22 19:11

Will