16,554
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ListBoxOverwrite
{
class MyListBox : ListBox
{
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (DesignMode || Enabled)
{
base.OnDrawItem(e);
return;
}
// Set the DrawMode property to draw fixed sized items.
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 normalBrush = Brushes.Black;
Brush selectedBrush = Brushes.White;
// Draw the current item text based on the current Font and the custom brush settings.
if (e.Index == SelectedIndex)
e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, selectedBrush, e.Bounds, StringFormat.GenericDefault);
else
e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, normalBrush, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
if (Enabled)
DrawMode = DrawMode.Normal;
else
DrawMode = DrawMode.OwnerDrawFixed;
Refresh();
}
}
}