準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にリストボックス (listBox1) を配置します。
サンプルコード (C#)
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
listBox1.ItemHeight = 20;
foreach (FontFamily item in FontFamily.Families)
{
if (item.IsStyleAvailable(FontStyle.Regular))
{
listBox1.Items.Add(item.Name);
}
}
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == -1) return;
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),
new Font(listBox1.Items[e.Index].ToString(), 12),
new SolidBrush(Color.Black),
e.Bounds.X,
e.Bounds.Y);
}
}
}
解説
リストボックスのアイテムのフォントを個別に変更するには、オーナードローモードでアイテムを描画する必要があります。これは通常の Add メソッド実行時に呼ばれる DrawItem イベントを使います。
結果
動作確認環境
Visual Studio 2022 Professional (.NET8 C#12)
ログ
初版:2016.05.16 Visual Studio 2015 Professional (C# 6.0)
