c# - 检查 FontFamily 是否为 TrueType

标签 c# fonts c++-cli truetype

是否可以使用 C#、C++/CLI 或通过 P/调用 WinAPI 来确定某个字体系列是否为 TrueType 字体?

最后我希望得到这样的结果

bool result1 = CheckIfIsTrueType(new FontFamily("Consolas")); //returns true
bool result2 = CheckIfIsTrueType(new FontFamily("Arial")); // returns true
bool result3 = CheckIfIsTrueType(new FontFamily("PseudoSaudi")); // returns false
bool result4 = CheckIfIsTrueType(new FontFamily("Ubuntu")); // returns true
bool result5 = CheckIfIsTrueType(new FontFamily("Purista")); // returns false

当然,结果取决于目标操作系统及其字体......

最佳答案

它有处理异常的开销,但是FontFamily constructor如果提供的字体不是 TrueType,则抛出 ArgumentException:

public bool CheckIfIsTrueType(string font)
{
    try
    {
        var ff = new FontFamily(font)
    }
    catch(ArgumentException ae)
    {
        // this is also thrown if a font is not found
        if(ae.Message.Contains("TrueType"))
            return false;        

        throw;
    }
    return true;
}

深入研究 FontFamily 构造函数,它调用外部 GDIPlus 函数 GdipCreateFontFamilyFromName:

[DllImport("Gdiplus", SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
internal static extern int GdipCreateFontFamilyFromName(string name, HandleRef fontCollection, out IntPtr FontFamily);

如果字体不是 true type 字体,则返回代码 16。因此您可以绕过异常的开销:

public bool CheckIfIsTrueType(string name)
{
    IntPtr fontfamily = IntPtr.Zero;
    IntPtr nativeFontCollection = IntPtr.Zero ;

    int status = GdipCreateFontFamilyFromName(name, new HandleRef(null, nativeFontCollection), out fontfamily);

    if(status != 0)
        if(status == 16)  // not true type font)
            return false;
        else
            throw new ArgumentException("GDI Error occurred creating Font");

    return true;
}

显然,您可能想在代码中使用常量枚举,可以在 here 中找到。 ,并抛出更好的异常

关于c# - 检查 FontFamily 是否为 TrueType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32528726/

相关文章:

c# - 从 .Net 应用程序打开 Windows 7 帮助 (helpPane.exe)

c# - 使用 Microsoft.Web.Administration 库创建 IIS 应用程序会创建两个应用程序而不是一个

css - 从 Pango.FontDescription 设置 GtkEntry 字体

c++ - ^ 在 bool GetDeviceInformation(String ^ port, LibCECConfiguration ^configuration, uint32_t timeoutMs) 中是什么意思

.net - 如何断开 TcpClient 以允许新连接?

c# - 使用 TypeConverter.ConvertFromString() 解析自定义格式的字符串

时间:2019-03-17 标签:c#mysqlStoredProcedureInsert返回值

html - 如何获得漂亮的字体平滑? (以及如何模仿 Medium.com 字体样式?)

python - 如何使用 python-fontforge 生成描边字体

c++ - 包装在 C++/CLI 中使用 native 接口(interface)的 native C++ 代码