Color ListBox for .Net 2.0
因為工作關係,常需要寫測試軟體,偶爾會看到訪間的 Log 畫面是彩色的,也想動手將測試結果輸出彩色的
一般我都會用 ListBox 作為顯示畫面,因為 ListBox 以行為單位,很適合我的使用,但也很不幸的 .Net 並沒有辦法將 ListBox 每行用不同的顏色,不過其實還是可以讓他用 "畫" 的完成這項作業
首先先把 DrawMode 設定為 OwnerDrawVariable ,再加入 listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem) ,這時您就可以自己創作 ListBox 的顯示方式了
此時便可以用 e.Graphics.DrawString 畫出所要的有顏色字串
e.Graphics.DrawString((sender as ListBox).Items[e.Index].ToString(), e.Font, myBrush, e.Bounds.X, e.Bounds.Y);
Item 內有 pass fail 時要改變不同顏色,判斷後修改 myBrush 的顏色即可
if (e.Index >= 0 && (sender as ListBox).Items[e.Index].ToString().IndexOf("fail", StringComparison.CurrentCultureIgnoreCase) >= 0)
myBrush = Brushes.Red;
else if (e.Index >= 0 && (sender as ListBox).Items[e.Index].ToString().IndexOf("pass", StringComparison.CurrentCultureIgnoreCase) >= 0)
myBrush = Brushes.DarkGreen;
else
myBrush = Brushes.Black;
選取時反白當然也要考慮進去,改用 SolidBrush
myBrush = new SolidBrush(e.ForeColor);
完整的程式碼如下
public Form1()
{
InitializeComponent();
this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox1.Items.Add("This is test!!");
listBox1.Items.Add("Test pass!!");
listBox1.Items.Add("Test fail!!");
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
System.Drawing.Brush myBrush;
if ((e.State & DrawItemState.Selected) != DrawItemState.Selected )
{
// unselected
if (e.Index >= 0 && (sender as ListBox).Items[e.Index].ToString().IndexOf("fail", StringComparison.CurrentCultureIgnoreCase) >= 0)
myBrush = Brushes.Red;
else if (e.Index >= 0 && (sender as ListBox).Items[e.Index].ToString().IndexOf("pass", StringComparison.CurrentCultureIgnoreCase) >= 0)
myBrush = Brushes.DarkGreen;
else
myBrush = Brushes.Black;
}
else
{
myBrush = new SolidBrush(e.ForeColor);
}
if (e.Index >= 0)
e.Graphics.DrawString((sender as ListBox).Items[e.Index].ToString(), e.Font, myBrush, e.Bounds.X, e.Bounds.Y);
e.DrawFocusRectangle();
}
成果:

後註:缺點是改用繪圖後,顯示的效能會下降很多,建議如需快速大量顯示資料,可以考慮完成後再切回繪圖模式,或是僅顯示少量