Aug 31, 2010

Load And Use Custom Font Without Installing

How to load and use font, not installed in the system? Not always your application have enough rights to install custom font into system. For example in ClickOnce application.

RTFM? Bull Shit! When you need some functionality and look documentation anything looks so fine... before you start coding.

I wrote application for ClickOnce install. My application require custom font. How to use custom font whithout administrator privileges? I look MSDN documentation, find class PrivateFontCollection and see beautiful example. Three seconds and i have few lines code in my app. But nothing happens. Custom font doesn't appears!

Ok, i write test programm, and use complete example from MSDN. Same result! Looking example i see used font names - Arial, Courier New, Times New Roman... Why i not surprised this example works? Cause these fonts are preinstalled in system. Only complete idiot will delete these fonts!


I search internet and see something about SetCompatibleTextRenderingDefault method of Application. Visual Studio by default sets this method to false but for rumors should be true. I tried, but still get nothing.

More googling and i saw similar examples, only difference is new Font created using FontFamily, but no by face name, as in MSDN sample.

I tried to use FontFamily received from PrivateFontCollection and gotcha! Result is fine! If i not forget, i will send feedback to MSDN. (Update: already sent)

Sample:
Create empty Windows Forms project, add label on form. Add Form.OnLoad handler, add folowing lines:

PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile("C:\\Path To\\PALETX3.ttf");
label1.Font = new Font(pfc.Families[0], 16, FontStyle.Regular);

Result:

Voila!

More Questions? Recommended Book: C# Graphics Programming (Wrox Briefs)

2 comments:

  1. Hi, I followed a post also that can add the font as an embedded resource, pretty well explain

    this post

    ReplyDelete
  2. Hi, I followed a post also that can add the font as an embedded resource, pretty well explain

    this post

    ReplyDelete