How to install a windows font using C#

試著忘記壹切 提交于 2019-11-26 12:47:36

问题


How can I install a font using C#?

I tried copying the fonts using File.Copy() but I am not allowed due to access rights limitations (UnauthorizedException).

What should I do?


回答1:


You'll need a different approach installing fonts.

  • Use an installer (create a setup project) to install the fonts
  • Another (more easy) approach using a native method.

Declare the dll import:

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

In your code:

    // Try install the font.
    result = AddFontResource(@"C:\MY_FONT_LOCATION\MY_NEW_FONT.TTF");
    error = Marshal.GetLastWin32Error();

The source:

http://www.brutaldev.com/post/2009/03/26/Installing-and-removing-fonts-using-C

I put it together in a unit test, I hope that helps:

[TestFixture]
public class Tests
{
    // Declaring a dll import is nothing more than copy/pasting the next method declaration in your code. 
    // You can call the method from your own code, that way you can call native 
    // methods, in this case, install a font into windows.
    [DllImport("gdi32.dll", EntryPoint = "AddFontResourceW", SetLastError = true)]
    public static extern int AddFontResource([In][MarshalAs(UnmanagedType.LPWStr)]
                                     string lpFileName);

    // This is a unit test sample, which just executes the native method and shows
    // you how to handle the result and get a potential error.
    [Test]
    public void InstallFont()
    {
        // Try install the font.
        var result = AddFontResource(@"C:\MY_FONT_LOCATION\MY_NEW_FONT.TTF");
        var error = Marshal.GetLastWin32Error();
        if (error != 0)
        {
            Console.WriteLine(new Win32Exception(error).Message);
        }
    }
}

That should help you on your way :)




回答2:


   internal static void InstalarFuente(string NombreFnt,string RutaFnt)
    {
        string CMD = string.Format("copy /Y \"{0}\" \"%WINDIR%\\Fonts\" ", RutaFnt);
        EjecutarCMD(CMD);

        System.IO.FileInfo FInfo = new System.IO.FileInfo(RutaFnt);
        CMD = string.Format("reg add \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\" /v \"{0}\" /t REG_SZ /d {1} /f", NombreFnt, FInfo.Name);
        EjecutarCMD(CMD);
    }

    public static void EjecutarCMD(string Comando)
    {
        System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo("cmd.exe");
        Info.Arguments = string.Format("/c {0}", Comando);
        Info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        System.Diagnostics.Process.Start(Info);
    }


来源:https://stackoverflow.com/questions/14796162/how-to-install-a-windows-font-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!