简体   繁体   中英

How to install new font on user's PC programmatically using C# Winfows Form Application?

如何使用 C# Windows 窗体应用程序以编程方式在用户的 PC 上安装新字体,以便我可以在此应用程序中包含的报告中使用此字体?

You can try with this code base on AddFontResource

[DllImport("gdi32.dll", EntryPoint="AddFontResourceW", SetLastError=true)]
public static extern int AddFontResource([In][MarshalAs(UnmanagedType.LPWStr)]
                                         string lpFileName);

Code

      //Install the font.
      result = AddFontResource(@"C:\MY_FONT_LOCATION\MY_NEW_FONT.TTF");
      error = Marshal.GetLastWin32Error();
      if (error != 0)
      {
        Console.WriteLine(new Win32Exception(error).Message);
      }
      else
      {
        Console.WriteLine((result == 0) ? "Font is already installed." :
                                          "Font installed successfully.");
      }

According to docs of AddFontResource()

This function installs the font only for the current session. When the system restarts, the font will not be present. To have the font installed even after restarting the system, the font must be listed in the registry.

So the best option i found is to copy the font to windows font directory

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

And then add respective entries in registery,Like

Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts");
                    key.SetValue("My Font Description", "fontname.tff");
                    key.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM