gpt4 book ai didi

c# - 如何以编程方式使用通过 AddFontResource() 安装的字体?

转载 作者:太空狗 更新时间:2023-10-29 23:30:19 25 4
gpt4 key购买 nike

我正在使用 AddFontResource函数为当前登录 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));
}

AddFontResource 函数返回的 int 结果是 1,根据文档,这是已成功安装的字体数。

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.

然后我使用以下代码以编程方式测试字体。

private static bool IsFontInstalled(string fontName)
{
using (var testFont = new Font(fontName, 8))
{
return fontName.Equals(testFont.Name, StringComparison.InvariantCultureIgnoreCase);
}
}

但是 isFontInstalled 函数总是返回 false。

此函数运行一个简单的测试,它尝试使用已安装的字体名称创建一个字体。如果安装成功,新字体将具有所用字体的名称,如果未安装,它将默认为不同的系统字体名称。

注意我认识到我当前以编程方式验证字体安装的实现可能不适用于所有情况,请随意提出更好的验证方法,我假设部分问题可能是我当前的实现仅适用于验证使用注册表安装的字体。

我使用相同的功能来测试我通过注册表安装的字体是否已安装并且是否按预期工作。关于如何使用显然已安装的字体的任何见解?

根据文档:

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.

据我了解,当前 session 一直持续到用户注销为止,这应该包括该程序的测试功能。

最佳答案

根据 RemoveFontResourceA function 上的文档

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

我创建了一个快速应用程序,我在其中使用 AddFontResource 在有效字体上添加了字体,然后在相同的有效字体上调用了 RemoveFontResource,非零退出代码是回来。然后我做了相反的事情,使用 AddFontResource 添加了一个伪造的字体,并且 RemoveFontResource 返回了 0 退出代码。您可以使用它来验证字体是否实际安装,如果卸载成功,只需让验证方法重新安装字体即可。

希望对您有所帮助。

关于c# - 如何以编程方式使用通过 AddFontResource() 安装的字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31681327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com