2

I want to make a combobox in a c# .NET 4.5 Windows Forms application (note: not WPF) that displays all the truetype installed font on the system and that every font is formatted with the font it's representing ("Times" formatted with Times, "Arial" formatted with arial and so on).

How to do this?

Sinatr
  • 20,892
  • 15
  • 90
  • 319
Ale TheFe
  • 1,540
  • 15
  • 43

3 Answers3

7

Use ComboBox.DrawItem eventhandler.

public YourForm()
{
    InitializeComponent();

    ComboBoxFonts.DrawItem += ComboBoxFonts_DrawItem;           
    ComboBoxFonts.DataSource = System.Drawing.FontFamily.Families.ToList();
}

private void ComboBoxFonts_DrawItem(object sender, DrawItemEventArgs e)
{
    var comboBox = (ComboBox)sender;
    var fontFamily = (FontFamily)comboBox.Items[e.Index];
    var font = new Font(fontFamily, comboBox.Font.SizeInPoints);

    e.DrawBackground();
    e.Graphics.DrawString(font.Name, font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
}

For using ComboBox.DrawItem you need set ComboBox.DrawMode = DrawMode.OwnerDrawFixed

Fabio
  • 31,528
  • 4
  • 33
  • 72
0

You can use System.Drawing.FontFamily.Families, something like this

List<string> fonts = new List<string>();

foreach (FontFamily font in System.Drawing.FontFamily.Families)
{
    fonts.Add(font.Name);
}

.................. your logic
  • Yes, but doing this I'll have only the names of the fonts. The'll not be formatted – Ale TheFe Sep 04 '17 at 12:45
  • @AleTheFe You can use the name to find the font though... only problem is that the regular combobox doesn't take a font for each item (as far as I know) – EpicKip Sep 04 '17 at 12:47
  • @EpicKip this is exactly what I thought about so far :'( – Ale TheFe Sep 04 '17 at 12:48
  • @AleTheFe Maybe this: https://stackoverflow.com/questions/8644007/designing-a-custom-font-dialog-selector-for-c-sharp-that-filters-out-non-true-ty is what you're looking for – EpicKip Sep 04 '17 at 12:49
0

You can achieve this by following a project published couple of years ago here, https://www.codeproject.com/Articles/318174/Creating-a-WYSIWYG-font-ComboBox-using-Csharp

But instead of doing that, you can follow the Narek Noreyan steps and adding more, use a rich text box, whose text font will be changed after selecting a font family from the combo box.

Some code snippet here,

using System.Drawing.Text;
void mainformload(object sender, EventArgs s)
{
    InstalledFontCollection inf=new      InstalledFontCollection();
    foreach(Font family font in inf.Families)
        combobox.Items.Add(font.Name); //filling the font name
    //get the font name of the rich text box text
    combobox.Text=this.richtextbox.Font.Name.ToString();
    }
void comboboxselectionchanged(object sender, EventArgs e)
{
    richtextbox.Font=new Font(combobox.text, richtextbox.Font.Size);
}
Metzner88
  • 3
  • 4