Reputation: 16536
Is there a way to set the font of a Windows Forms Control in C# that will accept a comma separated list of fonts? I want something similar to how browsers interpret CSS font families where it goes down the list until it finds the first font installed on the computer.
Example:
string fontList = "Obscure Font1, Obscure Font2, Verdana"
textBox1.Font = new Font( FontFamilyFromHtml(fontList), FontStyle.Bold);
Is there anything built in to .NET or do you need to create a method that will split the string on commas, then test the installed font list for each one until a match is found?
Upvotes: 2
Views: 2199
Reputation: 38077
There is no out of the box API call, so you will have to split the string and search through the installed fonts.
Here is an implementation that uses the InstalledFontCollection to do just that:
private FontFamily FindFontByCSSNames(string cssNames)
{
string[] names = cssNames.Split(',');
System.Drawing.Text.InstalledFontCollection installedFonts = new System.Drawing.Text.InstalledFontCollection();
foreach (var name in names)
{
var matchedFonts = from ff in installedFonts.Families where ff.Name == name.Trim() select ff;
if (matchedFonts.Count() > 0)
return matchedFonts.First();
}
// No match, return a default
return new FontFamily("Arial");
}
Upvotes: 3