因為需要使用DrawMode自行DrawItem,所以需要將DrawMode設置為OwnerDrawVarialbe或OwnerDrawFixed模式,代碼如下:
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index >= 0)
{
e.DrawBackground();
Brush mybsh = Brushes.Black;
if (listBox4.Items[e.Index].ToString().IndexOf("[ERROR]") != -1)
{
mybsh = Brushes.Red;
}
// 焦點框
e.DrawFocusRectangle();
//文本
//e.Graphics.DrawString(listBox4.Items[e.Index].ToString(), e.Font, mybsh, e.Bounds, StringFormat.GenericDefault);
e.Graphics.DrawString(listBox4.Items[e.Index].ToString(), e.Font, mybsh, e.Bounds, null);
}
}
並對listbox增加事件:DrawItem事件設置為listBox_DrawItem
但是這樣就無法使用默認方式出現水平滾動條,那么需要對listbox增加事件listbox_MeasureItem,代碼如下:
private void listBox_MeasureItem(object sender, MeasureItemEventArgs e)
{
String lvsDisp = listBox.Items[e.Index].ToString();
SizeF lvSize = e.Graphics.MeasureString(lvsDisp, listBox.Font);
if (listBox.HorizontalExtent < lvSize.Width)
{
listBox.HorizontalExtent = (int)lvSize.Width + 10;
}
e.ItemHeight = (int)lvSize.Height;
e.ItemWidth = (int)lvSize.Width;
}
這樣就可以自動出現水平滾動條了。
