Home > Programming > [C#] システムフォントを列挙する

[C#] システムフォントを列挙する

image

foreach (FontFamily family in FontFamily.Families)
{
    if (family.IsStyleAvailable(FontStyle.Regular))
        comboBoxFonts.Items.Add(family);
}
comboBoxFonts.SelectedIndex
  = comboBoxFonts.Items.IndexOf(this.Font.FontFamily);

System.Windows.Drawing.FontFlamiliy で取れるみたいです。(via C# Programming)

System.Windows.Media にも似たようなクラスがありますね。WPFのときに使うのでしょうか。フォントによってはレギュラーもサポートしていないものがあって、描画しようとするとエラーがでるのでチェックの上弾いてます。

コレだけじゃ面白くないので、コンボボックスにしてみるありがちな例

private const int margin = 5;

private void comboBoxFonts_DrawItem
    (object sender, DrawItemEventArgs e)
{
    try
    {
        e.DrawBackground();
        if (e.State == DrawItemState.Focus) e.DrawFocusRectangle();

        Font f = new Font(
            (FontFamily)comboBoxFonts.Items[e.Index], this.Font.Size);

        Rectangle rect = new Rectangle(e.Bounds.Location, e.Bounds.Size);
        rect.Inflate(-margin, -margin);
        StringFormat format = new StringFormat();
        format.LineAlignment = StringAlignment.Center;

        e.Graphics.DrawString(
            f.Name, f, SystemBrushes.WindowText, rect, format);
    }
    catch (Exception exception)
    {
        MessageBox.Show(exception.Message);
    }
}

private void comboBoxFonts_MeasureItem
    (object sender, MeasureItemEventArgs e)
{
    try
    {
        Font f = new Font(
             (FontFamily)comboBoxFonts.Items[e.Index], this.Font.Size);

        e.ItemHeight = (int)e.Graphics.MeasureString(f.Name, f).Height;
        e.ItemHeight += margin * 2;
    }
    catch (Exception exception)
    {
        MessageBox.Show(exception.Message);
    }
 }

DrawMode を OwnerDrawVariable にしておいて、2つのイベントの中身を記述します。ちゃんとフォントがサポートする書体を事前にチェックしていれば、 try – catch は特に要らないかも。

最後に、ちょっと追加。

private void comboBoxFonts_SelectionChange
    Committed(object sender, EventArgs e)
{
    comboBoxFonts.Text
        = ((FontFamily)comboBoxFonts.SelectedItem).Name;
}

今回の例では、コンボボックスのリストに直接オブジェクトをぶち込んでるので、表示するときは人間様が分かりやすいように名前だけを表示するようにします。 SelectChangeComitted は人間様がリストを操作したときにだけ起こるイベントです。内部で操作された場合も発生する SelectedChange などとは少し違いますね。

Home > Programming > [C#] システムフォントを列挙する

My Friend Feed

http://friendfeed.com/daruyanagi

Google Analyticator

610
 Unique Visitors 
 (1 day) 
Powered By Google Analytics

Return to page top