ListBoxで任意に文字色・ListItem毎に背景色を指定したいとのオーダーで作成。
オーダーが増えるようなら、コントロール自体を作った方がいいかも(´-∀-`;)
この中では、fColorとbColorで色を指定していますが
指定の仕方はListItem毎にColorIndex(int)を持たせて
受け渡す形で作りました。
無理やりですが、Item毎の文字列の規定の位置に格納してます☆
//Form1のLoadイベントハンドラ
private void Form1_Load(object sender, System.EventArgs e)
{
ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
// EventHandlerの追加
ListBox1.DrawItem += new DrawItemEventHandler(ListBox1_DrawItem);
}
private void ListBox1_DrawItem(object sender
,System.Windows.Forms.DrawItemEventArgs e)
{
ListBox lb = (ListBox)sender;
//背景を描画する
e.DrawBackground();
if (e.Index > -1)
{
//文字を描画する色の選択
Brush b = null;
if ((e.State & DrawItemState.Selected) != DrawItemState.Selected)
{
int fColor = Convert.ToInt16(lb.Items[e.Index].ToString().Substring(59, 1));
int bColor = Convert.ToInt16(lb.Items[e.Index].ToString().Substring(60, 1));
Color[] FontColor = { Color.Black, Color.Red, Color.Blue };
Brush[] BackColor = { Brushes.White, Brushes.Red, Brushes.Blue };
// fColor,bColorで色を指定
b = new SolidBrush(FontColor[fColor]);
// 背景色を変更
e.Graphics.FillRectangle(BackColor[bColor], e.Bounds);
}
else
{
b = new SolidBrush(e.ForeColor);
}
//文字列の取得
string txt = ((ListBox)sender).Items[e.Index].ToString();
//文字列の描画
e.Graphics.DrawString(txt, e.Font, b, e.Bounds);
b.Dispose();
}
}