PDA

View Full Version : Custom fonts in application



Brainer
15-07-2009, 03:42 AM
In response to Paul's question (http://www.pascalgamedevelopment.com/forum/index.php?topic=4820.msg47574#msg47574), I wanted to write a simple tutorial, how to use fonts that aren't installed in our system.

1.) First of all, grab your favorite font from your favorite website. :)
2.) Put it in your application's directory and find a convenient name for it (fx. "font.ttf"). Also, check what's the name of font you're about to use.
3.) To start using this font, you have to call method called AddFontResource.

uses
ShellAPI;

procedure TForm1.FormCreate(Sender: TObject);
begin
AddFontResource('font.ttf');
end;

Also, we need to broadcast a message to all windows that we're using a new resource. It's a simple modification of the above snippet:

uses
ShellAPI;

procedure TForm1.FormCreate(Sender: TObject);
begin
AddFontResource('font.ttf');
SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
end;

4.) Now, if you want to use it with a Memo control, simply call:

Memo1.Font.Name := 'My Font';

5.) The last thing is to remove the font and tell every window we won't be using it anymore. This code clears things up:

uses
ShellAPI;

procedure TForm1.FormDestroy(Sender: TObject);
begin
RemoveFontResource('font.ttf');
SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
end;


It's been a while since I last used this code, I'm sure it worked under XP, but I'm not sure if it will under Vista. I'd appreciate any feedback. :)

paul_nicholls
15-07-2009, 05:10 AM
neat! nice one Brainer :)

cheers,
Paul

Chien
15-07-2009, 02:51 PM
One of my application used most the same method, under vista, it works!

:-[

Brainer
15-07-2009, 03:03 PM
Thanks, Chien. :)

Who's to say if it works under Windows 7? lol

WILL
15-07-2009, 11:43 PM
Very cool. Is this with Delphi alone? Or will it also work with Lazarus?

Would be quite useful if you wanted to distribute your own truetype fonts for your game, but didn't want to shove them into the users Windows/Fonts folder. :p

Brainer
16-07-2009, 05:38 AM
Nope, I think it'd work for Lazarus, too, hence those two procedures are consisted in Windows API.
AddFontResource: http://msdn.microsoft.com/en-us/library/dd183326%28VS.85%29.aspx
RemoveFontResource: http://msdn.microsoft.com/en-us/library/dd162922%28VS.85%29.aspx

You might also consider using AddFontResourceEx (http://msdn.microsoft.com/en-us/library/dd183327%28VS.85%29.aspx) and RemoveFontResourceEx (http://msdn.microsoft.com/en-us/library/dd162923%28VS.85%29.aspx). They allow to hide your font from other application, thus you don't have to use SendMessage to tell every other process there's a new font. :)

jdarling
16-07-2009, 02:20 PM
That method will work in Lazarus on Windows only. Some place I found a direct fon (universal font file) render for Lazarus but don't remember where now, and I'm too lazy to google around :)