Monday, 22 October 2012

Listing Font Names in Windows 8 C# XAML Apps

I thought this would be a two line job, but as often in Windows 8, things aren't always as you'd expect. All I wanted to do was list font names for a combo box picker, but found you need to use DirectX DirectWrite to get the font names.

There's an example of doing this in an HTML/JS app using a C++ interop here:

I can't really beleive we need to go to such lengths to do something so simple, but luckily SharpDX comes to the rescue (again). It's still a bit convoluted having to interrogate the DirectWrite font family collections, but loads easier than writing a C++ interop!

Here's a helper class I wrote to get font names:

using SharpDX.DirectWrite;
using System.Collections.Generic;
using System.Linq;

namespace WebberCross.Helpers
    public class FontHelper
        public static IEnumerable<string> GetFontNames()
            var fonts = new List<string>();

            // DirectWrite factory
            var factory = new Factory();

            // Get font collections
            var fc = factory.GetSystemFontCollection(false);

            for (int i = 0; i < fc.FontFamilyCount; i++)
                // Get font family and add first name
                var ff = fc.GetFontFamily(i);

                var name = ff.FamilyNames.GetString(0);

            // Always dispose DirectX objects

            return fonts.OrderBy(f => f);

1 comment: