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.
Asked
Active
Viewed 2,845 times
4

Nyan Cat
- 303
- 1
- 5
- 14
-
http://stackoverflow.com/questions/224865/how-do-i-get-all-installed-fixed-width-fonts – Daniel Feb 23 '14 at 07:17
-
GetTextMetrics() is too painful to pinvoke. The simple way is to check if the length of "mmmm" is equal to "iiii". – Hans Passant Feb 23 '14 at 14:35
2 Answers
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;
}

AndresRohrAtlasInformatik
- 508
- 4
- 7
0
Please find the following URL:
more also on:
http://www.codeproject.com/Articles/30040/Font-Survey-42-of-the-Best-Monospaced-Programming
Hope this helps.

Adel
- 1,468
- 15
- 18