I'm using the AddFontResource function to install a font locally for the current login session.
private void installFont(string fontPath)
{
IntPtr HWND_BROADCAST = new IntPtr(0xFFFF);
const int WM_FONTCHANGE = 0x1D;
string fontLocation = Environment.ExpandEnvironmentVariables(fontPath);
int result = AddFontResourceA(fontLocation);
//This is currently printing Number of Fonts Installed = 1
Console.WriteLine("Number of Fonts Installed = " + result);
SendMessage(HWND_BROADCAST, WM_FONTCHANGE);
PrivateFontCollection fontCol = new PrivateFontCollection();
fontCol.AddFontFile(fontLocation);
var actualFontName = fontCol.Families[0].Name;
Console.WriteLine("Font Installed? = " + IsFontInstalled(actualFontName));
}
The int result that the AddFontResource
function is returning is 1, which according to the documentation is the number of fonts that were successfully installed.
If the function succeeds, the return value specifies the number of fonts added.
If the function fails, the return value is zero. No extended error information is available.
I am then programmatically testing the font using the following code.
private static bool IsFontInstalled(string fontName)
{
using (var testFont = new Font(fontName, 8))
{
return fontName.Equals(testFont.Name, StringComparison.InvariantCultureIgnoreCase);
}
}
However the isFontInstalled
function is always returning false.
This function runs a simple test where it tries to create a Font using the installed Fonts name. If the installation is successful, the new font will have the name of the font used, if not installed it will default to a different System font name.
NOTE I recognize that my current implementation of verifying font installation programmatically may not work for all cases, feel free to suggest superior ways to verify, I assume part of the issue may be that my current implementation only works to verify fonts that were installed using the registry.
I use this same function to test if a font I install via the registry is installed and it works as expected. Any insights into how to use the font that was apparently installed?
According to the docs:
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.
To my understanding current session lasts until the user logs out, and that should include the test function of this program.
答案 0 :(得分:3)
根据RemoveFontResourceA function
上的文件如果函数成功,则返回值为非零值。
如果函数失败,则返回值为零。
我创建了一个快速应用程序,我在有效字体上使用thisfile.html
添加了字体,然后在同一个有效字体上调用了AddFontResource
,返回了非零退出代码。然后我做了相反的事情并使用RemoveFontResource
添加了伪造字体,AddFontResource
返回了0退出代码。您可以使用它来验证字体是否实际安装,如果成功卸载,只需让验证方法重新安装该字体。
希望有所帮助。
答案 1 :(得分:0)
您可以尝试:
private static bool IsFontInstalled(string fontName)
{
try
{
using (var testFontFam = new FontFamily(fontName))
{
return true;
}
}
catch
{
return false;
}
}