即使在 Windows 重新启动后,C# AddFontResource 也无法正常工作

标签 c# api fonts dllimport

我正在尝试使用以下代码使用 C# 代码安装字体。

调用 InstallFont 不会抛出任何异常并返回 1。我认为这表明它已经安装了字体。但是,无论是在 Windows 字体文件夹中还是在检查 InstalledFontCollection 时,该字体都没有出现在已安装字体列表中,它也没有显示在我的软件中。我试过安装后重启电脑,还是不行。

如果我通过在 Windows 资源管理器中双击并单击“安装字体”来手动安装文件,则安装没有问题。

我在 Windows 7 64 位操作系统上使用 C#、Visual Studio 2010、Microsoft .NET Framework 4.0。

如有任何帮助,我们将不胜感激。

非常感谢, 保罗

list 文件包括:

requestedExecutionLevel level="requireAdministrator" uiAccess="false"

申请代码:

[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
[DllImport("gdi32.dll", EntryPoint = "AddFontResourceW", SetLastError = true)]
public static extern int AddFontResource([In][MarshalAs(UnmanagedType.LPWStr)] string lpFileName);

public static int InstallFont()        
{
    InstalledFontCollection ifc = new InstalledFontCollection();

    if (ifc.Families.Any(item => item.Name == "Arial Narrow"))
        return 100; // Font already installed

    string filename = @"C:\Users\username\Downloads\ARIALN.TTF";

    const int WM_FONTCHANGE = 0x001D;
    const int HWND_BROADCAST = 0xffff;

    int added = AddFontResource(filename);
    SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);

    return added;
}

最佳答案

请务必查看有关 AddFontResource() 的 MSDN 库文章:

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.

InstalledFontCollection 类仅枚举实际安装的字体并忽略临时字体。编写注册表项并将文件复制到 c:\windows\fonts 是安装程序的职责。除了通过控制面板小程序,Microsoft 没有记录如何执行此操作。如果你想尝试一下,注册表项是 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts

关于即使在 Windows 重新启动后,C# AddFontResource 也无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13528479/

相关文章:

c# - 扫描图像寻找矩形

azure - 如何使用 Microsoft 图表和 PowerShell 过滤登录并获取特定用户的身份验证要求?

javascript - 请求交付方式不起作用 - 向 Monster 申请

json - WSO2 API Manager Auth 错误内容类型

html - 阿拉伯字体在 IE 11 中不起作用?

c# - 修改 ASP.NET 成员架构

c# - 如何在 C# 中使用具有 %UserProfile% 的字符串复制文件

ios - Photoshop 中的字体大小与 Xcode 中的字体大小相同吗?

java - 如何在 Mac OS X 中获取字体文件夹路径?

c# - 认识 WCF 解决方案