FontDropDownList and PrivateFontCollection

SyntaxEditor for Windows Forms Forum

Posted 9 years ago by Robert Muir
Avatar
I'm using the FontDropDownList control, which auto-populates itself with fonts. However I now need to use a PrivateFontCollection, but there appears to be no way of getting this additional font data into the FontDropDownList control.

Is there any solution to this?

Thanks

Comments (2)

Posted 9 years ago by Actipro Software Support - Cleveland, OH, USA
Avatar
Hi Robert,

You can probably clear the Items collection and then add FontDropDownList.FontFamilyData items to from your own collection.


Actipro Software Support

Posted 9 years ago by Robert Muir
Avatar
Thanks, that works.

For anyone else who wants to try it this might save some time:
        // Fixed Width fonts are displayed in bold in the drop down list

        static internal void PopulateFonts(FontDropDownList control, PrivateFontCollection pfc)
        {
            control.Items.Clear();
            List<FontDropDownList.FontFamilyData> fonts = new List<FontDropDownList.FontFamilyData>();
            using (Graphics g = control.CreateGraphics())
            {
                using (InstalledFontCollection installed_font_collection = new InstalledFontCollection())
                {
                    GetFontFamilyData(g, installed_font_collection.Families, fonts);
                }
                GetFontFamilyData(g, pfc.Families, fonts);
            }

            // Sort and remove duplicates from list

            fonts.Sort((first, second) => first.Name.CompareTo(second.Name));
            Int32 index = 0;
            while (index < fonts.Count - 1)
            {
                if (fonts[index].Name == fonts[index + 1].Name)
                    fonts.RemoveAt(index);
                else
                    index++;
            }
            control.Items.AddRange(fonts.ToArray());
        }

        static void GetFontFamilyData(Graphics g, FontFamily[] font_families, List<FontDropDownList.FontFamilyData> fonts)
        {
            foreach (FontFamily font_family in font_families)
            {
                fonts.Add(new FontDropDownList.FontFamilyData(font_family.Name, IsFixedWidth(g, font_family)));
            }
        }

        static bool IsFixedWidth(Graphics g, FontFamily ff)
        {
            if (ff.IsStyleAvailable(FontStyle.Regular))
            {
                using (Font font = new Font(ff, 10, FontStyle.Regular))
                {
                    return g.MeasureString("iii", font).Width == g.MeasureString("WWW", font).Width;
                }
            }
            return false;
        }
The latest build of this product (v2018.1 build 0341) was released 10 months ago, which was after the last post in this thread.

Add Comment

Please log in to a validated account to post comments.