4

I have a System.Drawing.Font object. How I can check is that font is monospace? I tried something like font.FontFamily == FontFamily.GenericMonospace, but it's not properly working.

Nyan Cat
  • 303
  • 1
  • 5
  • 14

2 Answers2

1

In C# WPF an easy but a little bit expensive method goes like that:

    private static char[] charSizes = new char[] { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' };

    private bool IsMonospaced(FontFamily family)
    {
        foreach (Typeface typeface in family.GetTypefaces())
        {
            double firstWidth = 0d;

            foreach (char ch in charSizes)
            {
                FormattedText formattedText = new FormattedText(
                    ch.ToString(),
                    CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    typeface,
                    10d,
                    Brushes.Black,
                    new NumberSubstitution(),
                    1);
                if (ch == 'i')  // first char in list
                {
                    firstWidth = formattedText.Width;
                }
                else
                {
                    if (formattedText.Width != firstWidth)
                        return false;
                }
            }
        }

        return true;
    }