Condividi tramite


Enumerating installed fonts using SharpDX DirectWrite and XAML in a Windows 10 Store App (UWP)

 

When dealing with fonts, many apps show a Combo Box listing all the fonts installed on the system and allow the user to choose from them. However, this functionality is not directly supported in XAML, so to implement this in a Windows Store Universal Windows Platform (UWP) app we need to dip into some SharpDX.

Here’s what the sample looks like:

 

image

 

The combo box lists all the installed fonts and allows the user to pick from one, setting the font on the text box.

 

This is relatively easy once you’ve added a reference to SharpDX as it provides a GetSystemFontCollection method that pretty much does this. We just wrap it in some code to make it easy to call.

 

// Code taken straight from SharpDX\Samples\DirectWrite\FontEnumeration\Program.cs
public static List<InstalledFont> GetFonts()
{
if(fonts != null)
return fonts;
var fontList = new List<InstalledFont>();

    using (var factory = new Factory())
{
using (var fontCollection = factory.GetSystemFontCollection(false))
{
var familyCount = fontCollection.FontFamilyCount;
for (int i = 0; i < familyCount; i++)
{
try
{
using (var fontFamily = fontCollection.GetFontFamily(i))
{
var familyNames = fontFamily.FamilyNames;
int index;

                        if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out index))
familyNames.FindLocaleName("en-us", out index);

                        string name = familyNames.GetString(index);
string display = name;
using (var font = fontFamily.GetFont(index))
{
if (font.IsSymbolFont)
display = "Segoe UI";
}

                        fontList.Add(new InstalledFont { Name = name, DisplayFont = display });
}
}
catch { } // Corrupted font files throw an exception - ignore them
}
}
}

    fontList.Sort();
fonts = fontList;
return fontList;
}

 

I noticed when calling this that some systems have corrupt font files and the above call throws an exception when querying for IsSymbolFont. It is much better to have the exception in this method than later when we try to use the font, as here we can just ignore it.

 

I have provided a sample project with all the code hooked up. You are free to use it in your code, even for commercial use.

 

https://theuxblog20160710035436.azurewebsites.net/FontSample.zip

 

Enjoy!

Paul Tallett, UX Global Practice, Microsoft UK

Disclaimer: The information on this site is provided "AS IS" with no warranties, confers no rights, and is not supported by the authors or Microsoft Corporation. Use of included script samples are subject to the terms specified in the Terms of Use.