用可用字体列表填充下拉框

48

如何用系统中所有可用字体列表填充下拉框?


请查看以下示例(http://www.java2s.com/Code/CSharp/GUI-Windows-Form/Loadallsysteminstalledfonts.htm)(http://www.java2s.com/Code/CSharp/GUI-Windows-Form/Loadallsysteminstalledfonts.htm),(http://www.java2s.com/Code/CSharp/GUI-Windows-Form/Fontlist.htm)(http://www.java2s.com/Code/CSharp/GUI-Windows-Form/Fontlist.htm)。 - thelost
@thelost,该链接不再存在。 - Massimiliano Kraus
7个回答

71
你可以使用 System.Drawing.FontFamily.Families 来获取可用的字体。
List<string> fonts = new List<string>();

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

// add the fonts to your ComboBox here

我安装了Montserrat字体。这段代码没有列出Montserrat字体,但Microsoft Word和控制面板外观和可视化都可以列出该字体。那么问题出在哪里?该字体的下载链接是https://www.fontsquirrel.com/fonts/montserrat。 - Tomas Kubes
1
我明白了。这段代码仅列出TrueType字体,请参见此修复程序https://dev59.com/4kXRa4cB1Zd3GeqPveRt - Tomas Kubes

12

不确定为什么我们需要在这里使用foreach

IList<string> fontNames = FontFamily.Families.Select(f => f.Name).ToList();

我在想。但既然它是可枚举的,难道不还需要 foreach 吗?还是说 C#有类似于 Python 生成器的语法? - Jamie
2
IList<string> fontNames = FontFamily.Families.Select(f => f.Name).ToList();ComboBox 不接受 IEnumerable - Nicke Manarin

4

3

这是一种简单的方法。它包括两个下拉框,一个用于字体名称,另一个用于字体大小。

 public FontFamily[] Families { get; }


 private void Form1_Load(object sender, EventArgs e)
    {

        foreach (FontFamily oneFontFamily in FontFamily.Families)
        {
            comboBox1.Items.Add(oneFontFamily.Name);
        }

        comboBox1.Text = this.richTextBox1.Font.Name.ToString();
        comboBox2.Text = this.richTextBox1.Font.Size.ToString();

        richTextBox1.Focus();

    }

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {

         float size = Convert.ToSingle(((ComboBox)sender).Text);

        richTextBox1.SelectionFont = new Font(richTextBox1.Font.FontFamily, size);
    }

1
请记住,所有内容都将来自“System.Drawing”。
foreach (System.Drawing.FontFamily font in System.Drawing.FontFamily.Families)
{
    comboBox1.Items.Add(font.Name);
}

0
ComboBox1.ItemsSource = new InstalledFontCollection().Families;

并且第一次选择的项目:

private void Combo1_Loaded(object sender, RoutedEventArgs e)
{
    ComboBox1.Text = "Tahoma";
}

-1

你只需要像这样绑定:

ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接