winform listbox 使用DrawMode使用OwnerDrawVarialbe或OwnerDrawFixed无水平滚动条
因为需要使用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;
}
这样就可以自动出现水平滚动条了。
浙公网安备 33010602011771号