即使在 Windows 重新启动后,C# AddFontResource 也不起作用
我正在尝试使用以下代码使用 C# 代码安装字体.
I'm trying to install a font using C# code using the code below.
调用 InstallFont 不会抛出任何异常并返回 1.我认为这表明它已安装字体.但是,无论是在 Windows Fonts 文件夹中还是在检查 InstalledFontCollection 时,该字体都不会出现在已安装字体列表中,也不会出现在我的软件中.安装后我尝试重新启动计算机,但它仍然不可用.
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():
此功能仅为当前会话安装字体.当系统重新启动时,字体将不存在.要在重新启动系统后安装字体,字体必须在注册表中列出.
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
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