问题
First Try
Here is what we get for the Arial TTF font:
Here is what we get for the Sitka TTC font:
And here is what we get for the SimSun TTC font:
I tried to use the OpenFontReader
object from the Typography.OpenFont.NetCore package.
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Typography.OpenFont;
namespace MyApp
{
class Program
{
static async Task Main(string[] args)
{
var fontName1 = GetRegistryFontName(@"C:\Windows\Fonts\arial.ttf");
var fontName2 = GetRegistryFontName(@"C:\Windows\Fonts\Sitka.ttc");
var fontName3 = GetRegistryFontName(@"C:\Windows\Fonts\simsun.ttc");
Console.WriteLine("Press a key to exit...");
Console.ReadKey();
}
static string GetRegistryFontName(string fontFile)
{
var fontReader = new OpenFontReader();
var fontInfo = fontReader.ReadPreview(File.OpenRead(fontFile));
var fontExtension = Path.GetExtension(fontFile).ToLower();
var fontTypeSuffix = (fontExtension == ".otc" || fontExtension == ".otf") ? "(OpenType)" : "(TrueType)";
if (fontExtension == ".otf" || fontExtension == ".ttf")
{
return $"{fontInfo.Name} {fontInfo.SubFamilyName} {fontTypeSuffix}";
}
else if (fontExtension == ".otc" || fontExtension == ".ttc")
{
var fontNames = fontInfo.Name.Split(",").Skip(1).ToArray();
var result = new StringBuilder(fontNames[0]);
foreach (var fontName in fontNames[1..^1])
{
result.Append($" & {fontName}");
}
result.Append($" & {fontNames[^1]} {fontTypeSuffix}");
return result.ToString();
}
return null;
}
}
}
And here is the result:
It's almost working but there are two problems:
- The name for the
arial.ttf
font isArial (TrueType)
in the Registry andArial Normal (TrueType)
in my result. - I get an Asian name for the
simsun.ttc
font withOpenFontReader
.
Second Try
I tried using the fontview and the FlaUI package.
using FlaUI.Core;
using FlaUI.Core.Tools;
using FlaUI.UIA3;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace MyApp
{
class Program
{
static async Task Main(string[] args)
{
var fontName1 = GetRegistryFontName(@"C:\Windows\Fonts\arial.ttf");
Console.WriteLine("Press a key to exit...");
Console.ReadKey();
}
static string GetRegistryFontName(string fontFile)
{
var psi = new ProcessStartInfo()
{
FileName = "fontview",
Arguments = fontFile
};
string fontName = null;
var app = Application.Launch(psi);
using (var automation = new UIA3Automation())
{
var window = Retry.WhileNull(() =>
app.GetMainWindow(automation),
TimeSpan.FromSeconds(10)
).Result;
window.SetTransparency(0);
window.Focus();
fontName = window.Title;
window.Close();
}
return fontName;
}
}
}
The result is even more weird:
The Arial font is now an OpenType font. Thank you Windows. :)
Do you have a solution to recover the same name as in the Registry?
It should work with any font even external ones and with .NET Core.
来源:https://stackoverflow.com/questions/60017050/how-to-get-font-name-like-in-the-windows-registry-with-c