InstalledFontCollection

InstalledFontCollection

本文介绍了即使Windows重新启动后,C#AddFontResource也无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to install a font using C# code using the code below.

调用InstallFont不会引发任何异常并返回1.我认为这表明它已安装字体.但是,该字体既不会出现在Windows字体文件夹中,也不会出现在Windows字体文件夹中的已安装字体列表中,也不会在我的软件中显示.我已尝试在安装后重新启动计算机,但仍无法使用.

Calling InstallFont doesn't throw any exceptions and returns 1. I thought this indicated it's installed the font. However the font does not appear in the list of installed fonts either in the Windows Fonts folder or when checking InstalledFontCollection, neither is it displayed in my software. I have tried restarting the computer after install but it is still not available.

如果我通过在Windows资源管理器中双击并单击安装字体来手动安装文件,则安装不会出现问题.

If I install the file manually by double clicking in Windows Explorer and clicking Install the font installs without issue.

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

I am using C#, Visual Studio 2010, Microsoft .NET Framework 4.0 on a Windows 7 64bit operating system.

任何帮助将不胜感激.

非常感谢,保罗

清单文件包括:

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库文章:

Be sure to look at the MSDN Library article for AddFontResource():

InstalledFontCollection类仅枚举实际安装的字体,并省略临时字体.编写注册表项并将文件复制到c:\ windows \ fonts是非常重要的安装任务.除了通过控制面板"小程序进行操作之外,Microsoft没有记录如何执行此操作.如果您想尝试一下,注册表项是HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ Fonts

The InstalledFontCollection class only enumerates fonts that are actually installed and omits the temporary ones. Writing the registry keys and copying the file to c:\windows\fonts is very much an installer duty. Microsoft does not document how to do that, other than going to through the Control Panel applet. If you want to take a shot at it, the registry key is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts

这篇关于即使Windows重新启动后,C#AddFontResource也无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:49