Reputation: 109
I'm trying to install a font using C# code using the code below.
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.
If I install the file manually by double clicking in Windows Explorer and clicking Install the font installs without issue.
I am using C#, Visual Studio 2010, Microsoft .NET Framework 4.0 on a Windows 7 64bit operating system.
Any help would be greatly appreciated.
Many Thanks, Paul
Manifest file includes:
requestedExecutionLevel level="requireAdministrator" uiAccess="false"
Application code:
[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;
}
Upvotes: 4
Views: 6758
Reputation: 941208
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.
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
Upvotes: 7