1

I want to install font, but my code is not working.How can I install a new font on user's PC programmatically using C# Windows Form Application so that I can use this font in the report included in this application ?

This my code :

namespace Font
{
    public partial class Form1 : Form
    {
        [DllImport("gdi32.dll", EntryPoint = "AddFontResourceW", SetLastError = true)]
        public static extern int AddFontResource([In][MarshalAs(UnmanagedType.LPWStr)]
        string lpFileName);

        public void InstallFont()
        {

            var result = AddFontResource(@"D:\Temp\BAseman.TTF");
            var error = Marshal.GetLastWin32Error();
        }

        public Form1()
        {
            InitializeComponent();
        }
        private void btnInstall_Click(object sender, EventArgs e)
        {
            InstallFont();
        }
    }
}

1 Answers1

0

Installing a font is as simple as copying it to the Fonts directory. So, just do this:

File.Copy("MyNewFont.ttf",
    Path.Combine(Environment.GetFolderPath(SpecialFolder.Windows),
        "Fonts", "MyNewFont.ttf"));

However, there are some caveats here.

  1. The user needs to have admin rights and the OS will prompt for them.
  2. The font needs to reside in the executing folder of your application for my code to work exactly.

You could continue to use that Windows API, but it's going to be more difficult likely.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232