如何使用C#安装Windows字体

问题描述 投票:0回答:3

如何使用 C# 安装字体?

我尝试使用

File.Copy()
复制字体,但由于访问权限限制,我不被允许 (
UnauthorizedException
)。

我该怎么办?

c# fonts access-denied unauthorized
3个回答
18
投票

您需要采用不同的方法来安装字体。

  • 使用安装程序(创建安装项目)来安装字体
  • 使用本机方法的另一种(更简单)方法。

声明 dll 导入:

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

在您的代码中:

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

来源:

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

我将其放在单元测试中,希望有帮助:

[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);
        }
    }
}

这应该对你有帮助:)


1
投票
   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);
    }

0
投票

如果有人最近发现 Windows\Fonts 文件夹的访问被拒绝(现在 2024 年 11 月 16 日), 项目 -> 添加 -> 清单添加 和 像这样设置清单

<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    <requestedExecutionLevel level="highestAvailable" uiAccess="false" />
  </requestedPrivileges>
  
© www.soinside.com 2019 - 2024. All rights reserved.