AddFontResource (gdi32)
Last changed: -79.207.112.186

.
Summary
Adds the font resource from the specified file to the system font table.

C# Signature:

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

User-Defined Types:

None.

Notes:

To mark a font as private or non-enumerable, use the AddFontResourceEx function.

Tips & Tricks:

Use SendMessageTimeout or PostMessage instead of SendMessage. SendMessage may hang which will hang your application/installer.

SendMessageTimeout allows you to enter timeout value.

PostMessage will add message to the windows queue.

Sample Code:

  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.IO;
  using System.Runtime.InteropServices;

  namespace FontResource
  {
    class Program
    {
    private static IntPtr HWND_BROADCAST = new IntPtr(0xffff);
    private static IntPtr HWND_TOP = new IntPtr(0);
    private static IntPtr HWND_BOTTOM = new IntPtr(1);
    private static IntPtr HWND_TOPMOST = new IntPtr(-1);
    private static IntPtr HWND_NOTOPMOST = new IntPtr(-2);
    private static IntPtr HWND_MESSAGE = new IntPtr(-3);

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

    [DllImport("gdi32.dll")]
    static extern bool RemoveFontResource(string lpFileName);

    [DllImport("user32.dll",CharSet=CharSet.Auto)]
    private static extern int SendMessage(IntPtr hWnd, WindowsMessages wMsg, IntPtr wParam, IntPtr lParam);

    static void Main(string[] args)
    {
        if (args.Length < 2) { Usage(); return; }

        FileInfo fontFile = new FileInfo(args[1]);

        if (!fontFile.Exists)
        {
        Console.WriteLine("Font file not found.\n");
        Usage();
        return;
        }

        switch (args[0]) {
        case "add" :
            AddFontResource(args[1]);
            break;
        case "rem" :
            RemoveFontResource(args[1]);
            break;
        default :
            Usage();
            return;
        }

        //This version of SendMessage is a blocking call until all windows respond.
        long result = SendMessage(HWND_BROADCAST, WindowsMessages.WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero);

       //Alternatively PostMessage instead of SendMessage to prevent application hang
       //bool posted = API.PostMessage(HWND_BROADCAST, WindowsMessages.WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero);

        Console.WriteLine(String.Format("WM_FONTCHANGE broadcast returned {0}", result));
    }

    public static void Usage()
    {
        Console.WriteLine("FontResource [add|rem] <font>");
        Console.WriteLine("\nAny changes will not persist a reboot - to do so, remove the font entry from the registry.");
    }

    public enum WindowsMessages
    {
        //Snipped for length - see the list of WM_ calls on this site.
    }

Alternative Managed API:

Do you know one? Please contribute it!

Documentation