Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

fonts

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?

like image 306
Keith Palmer Jr. Avatar asked Oct 08 '22 13:10

Keith Palmer Jr.


1 Answers

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());
}
like image 92
Alex Mendez Avatar answered Oct 12 '22 22:10

Alex Mendez