Keith Palmer Jr.
Keith Palmer Jr.

Reputation: 27952

Font doesn't exist and crashes the .NET application, need to check for or install the font

Deploying a C# .NET application, our GUI elements use the "Arial" font (that's the default in the Visual Studio GUI designer thing).

One particular customer we're working with for some reason didn't have the Arial font installed (they must have manually deleted it, since as far as I know it comes by default with all Windows installs).

This results in an exception/application crash.

Is there some way to make sure a font exists with C#, and/or install it automatically if it doesn't?

Upvotes: 5

Views: 903

Answers (2)

Alex Mendez
Alex Mendez

Reputation: 5150

You need to embed the font as a resource and then do something similar to this:

[DllImport("gdi32", EntryPoint = "AddFontResource")]
public static extern int AddFontResourceA(string lpFileName);

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    List<FontFamily> fontsFamilies = new List<FontFamily>(FontFamily.Families);
    if (!fontsFamilies.Exists(f => f.Name.Equals("Arial")))
    {
        //Save the font from resource here....


        //Install the font
        int result = AddFontResourceA(@"C:\MY_FONT_LOCATION\Arial.TTF");
    }

    Application.Run(new Form1());
}

Upvotes: 4

Sam Axe
Sam Axe

Reputation: 33738

Embed the font as a resource and check for/install it before you display any UI elements.

Upvotes: 0

Related Questions