c# - 如何使用 C# 安装 Windows 字体

标签 c# fonts access-denied unauthorized

如何使用 C# 安装字体?

我尝试使用 File.Copy() 复制字体,但由于访问权限限制(UnauthorizedException)不允许我这样做。

我该怎么办?

最佳答案

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

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

声明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);
        }
    }
}

这应该对您有所帮助:)

关于c# - 如何使用 C# 安装 Windows 字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14796162/

相关文章:

c# - Windows 窗体在显示消息前等待 5 秒

c# - Entity Framework : How does the data context deal with duplicate objects?

linux - Linux 上的 PDF : Combine font subsets and replace Type 3 with Type 1

JavaFx : java. io.FileNotFoundException(访问被拒绝)

c# - WPF NotifyIcon 首次运行时崩溃 - VisualTarget 的根视觉对象不能有父对象

c# - 在 Visual Studio 中打开项目/解决方案和打开网站有哪些区别?

css - 移动设备上的 Comic Sans MS

python - 倒字形 : bitmap > SVG via autotrace > glyph via fontforge

python - Selenium python - 启动 Firefox webdriver 时拒绝访问/hub/session

java - 在 NAS 上移动文件时出现 AccessDeniedException