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

时间:2012-11-23 11:45:27

标签: c# api fonts dllimport

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

调用InstallFont不会抛出任何异常并返回1.我认为这表明它已经安装了字体。但是,在Windows Fonts文件夹中或者在检查InstalledFontCollection时,字体不会出现在已安装字体列表中,也不会在我的软件中显示。我已经尝试在安装后重新启动计算机,但它仍然无法使用。

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

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

非常感谢任何帮助。

非常感谢, 保罗

清单文件包括:

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

1 个答案:

答案 0 :(得分:6)

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

  

此功能仅为当前会话安装字体。系统重新启动时,字体将不存在。要在重新启动系统后安装字体,必须在注册表中列出该字体。

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