Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get all installed fixed-width fonts?

I'm wondering if there are any simple ways to get a list of all fixed-width (monospaced) fonts installed on a user's system in C#?

I'm using .net 3.5 so have access to the WPF System.Windows.Media namespace and LINQ to get font information, but I'm not sure what I'm looking for.

I want to be able to provide a filtered list of monospaced fonts and/or pick out monospaced fonts from a larger list of fonts (as seen in the VS options dialog).

like image 261
Nidonocu Avatar asked Oct 22 '08 08:10

Nidonocu


2 Answers

Have a look at:

http://www.pinvoke.net/default.aspx/Structures/LOGFONT.html

Use one of the structures in there, then loop over families, instantiating a Font, and getting the LogFont value and checking lfPitchAndFamily.

The following code is written on the fly and untested, but something like the following should work:

foreach (FontFamily ff in System.Drawing.FontFamily.Families)
{
    if (ff.IsStyleAvailable(FontStyle.Regular))
    {
        Font font = new Font(ff, 10);
        LOGFONT lf = new LOGFONT();
        font.ToLogFont(lf);
        if (lf.lfPitchAndFamily ^ 1)
        {
            do stuff here......
        }
    }
}
like image 163
Tim Ebenezer Avatar answered Sep 20 '22 02:09

Tim Ebenezer


Unfortunately ToLogFont function does not fill lfPitchAndFamily field to correct values. In my case it's always 0.

One approximation to detect which fonts might be fixed is the following

    foreach ( FontFamily ff in FontFamily.Families ) {
            if ( ff.IsStyleAvailable( FontStyle.Regular ) ) {
                float diff;
                using ( Font font = new Font( ff, 16 ) ) {
                    diff = TextRenderer.MeasureText( "WWW", font ).Width - TextRenderer.MeasureText( "...", font ).Width;
                }
                if ( Math.Abs( diff ) < float.Epsilon * 2 ) {
                    Debug.WriteLine( ff.ToString() );
                }
            }

        }

Keep in mind that they are several false positives, for example Wingdings

like image 37
Panos Theof Avatar answered Sep 19 '22 02:09

Panos Theof