Friday 31 July 2009

Installing True Type fonts in a C# WPF application

I just had to install fonts into the Windows fonts folder for the application I'm developing as I wanted to use Segoe UI as it renders well in very small sizes.
I read a whole bunch of posts that used

[DllImport("gdi32.dll")]
static extern int AddFontResource(string lpszFilename);

I tried that, but it wasn't working for me so I went down the simpler path of just copying my .ttf files into the windows\fonts directory. Seems to work fine. I suspect there could be permission options if your application doesn't have the right level of trust - but that's not an issue with what I'm doing. Code is as follows. Make sure the fonts are in your solution and are being copied to the output directory of your application:

private static void InstallFonts()
{
try
{
var windowsDirectory = Environment.GetEnvironmentVariable("SystemRoot") + "/Fonts/";
var directoryInfo = new DirectoryInfo();

foreach(var file in directoryInfo.GetFiles())
{
InstallIfNotExists(file, windowsDirectory);
}
catch (Exception ex)
{
// Do something
}
}
}

private static void InstallIfNotExists(FileInfo file, string windowsDirectory)
{
var destination = new FileInfo(windowsDirectory + file.Name);

if (!destination.Exists)
file.CopyTo(destination.ToString());
}