[C#]List Box 更改顯示顏色

需求又變更摟

所以要加這東西

cOW!!

先到ListBox的屬性視窗把  DrawMode 修改成 OwnerDrawFixed

然後在LstBox的事件中加入事件函式 如下


private void EventLogDrawItem(object sender, DrawItemEventArgs e)
{
// Set the DrawMode property to draw fixed sized items.
this.EvnetLogListBox.DrawMode = DrawMode.OwnerDrawFixed;
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Define the default color of the brush as black.
Brush myBrush = Brushes.Black;


String str = EvnetLogListBox.Items[e.Index].ToString();
int type = 0;
if (str.IndexOf("ALERT") != -1)type = 0;
else if (str.IndexOf("CRITICAL") != -1) type = 1;
else if (str.IndexOf("ERROR") != -1) type = 2;
else if (str.IndexOf("WARNING") != -1) type = 3;
else if (str.IndexOf("INFO") != -1) type = 4;
else if (str.IndexOf("DEBUG") != -1) type = 5;

// Determine the color of the brush to draw each item based on the index of the item to draw.
switch (type)
{
case 0:
myBrush = Brushes.Red;
break;
case 1:
myBrush = Brushes.Orange;
break;
case 2:
myBrush = Brushes.Blue;
break;
case 3:
myBrush = Brushes.OrangeRed;
break;
case 4:
myBrush = Brushes.Green;
break;
case 5:
myBrush = Brushes.Black;
break;
}

// Draw the current item text based on the current Font and the custom brush settings.
e.Graphics.DrawString(EvnetLogListBox.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}

留言

這個網誌中的熱門文章

工作後寫程式的收穫