您可以根据原始列表创建自己的列表框。首次编译新列表后,它将出现在工具箱中,以便您可以将其拖放到表单中。或者您可以在 Form.designer.cs 中手动将现有列表框的类型更改为ListBoxEx。
public class ListBoxEx : ListBox
{
public ListBoxEx()
{
DrawMode = DrawMode.OwnerDrawFixed;
DoubleBuffered = true; // Eliminates flicker (optional).
}
private int _hotTrackedIndex = -1;
private int HotTrackedIndex
{
get => _hotTrackedIndex;
set {
if (value != _hotTrackedIndex) {
if (_hotTrackedIndex >= 0 && _hotTrackedIndex < Items.Count) {
Invalidate(GetItemRectangle(_hotTrackedIndex));
}
_hotTrackedIndex = value;
if (_hotTrackedIndex >= 0) {
Invalidate(GetItemRectangle(_hotTrackedIndex));
}
}
}
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
var borderRect = e.Bounds;
borderRect.Width--;
borderRect.Height--;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) {
if (Focused) {
e.Graphics.FillRectangle(Brushes.Teal, e.Bounds);
e.Graphics.DrawRectangle(Pens.LightSkyBlue, borderRect);
} else {
e.Graphics.FillRectangle(Brushes.DimGray, e.Bounds);
e.Graphics.DrawRectangle(Pens.White, borderRect);
}
} else if (e.Index == HotTrackedIndex) {
e.Graphics.FillRectangle(Brushes.DarkSlateGray, e.Bounds);
e.Graphics.DrawRectangle(Pens.DarkCyan, borderRect);
} else {
e.DrawBackground();
}
if (Items[e.Index] != null) {
e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, Brushes.White, 6, e.Bounds.Top, StringFormat.GenericTypographic);
}
}
protected override void OnMouseLeave(EventArgs e)
{
HotTrackedIndex = -1;
base.OnMouseLeave(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
HotTrackedIndex = IndexFromPoint(e.Location);
base.OnMouseMove(e);
}
protected override void OnGotFocus(EventArgs e)
{
if (SelectedIndex >= 0) {
RefreshItem(SelectedIndex);
}
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e)
{
if (SelectedIndex >= 0) {
RefreshItem(SelectedIndex);
}
base.OnLostFocus(e);
}
}
我们通过覆盖OnDrawItem 来更改列表框的外观。在构造函数中,我们设置DrawMode = DrawMode.OwnerDrawFixed; 启用所有者绘图。
我们必须考虑选中项目和热跟踪项目,即鼠标移动过的项目。如果要绘制的项目是选中的,我们进一步区分列表框有焦点或没有焦点的情况。
FillRectangle 绘制背景。 DrawRectangle 绘制边框。注意边框矩形必须比e.Bounds矩形小一个像素,否则不会绘制右下边框。
如果当前项没有被选中,我们测试它是否是热跟踪的。如果是,我们用不同的颜色绘制。否则我们使用e.DrawBackground(); 绘制默认背景。
然后我们用DrawString在背景上绘制文本。
为了使所有这些工作,我们还必须使列表框的颜色发生变化的区域无效。我们在OnMouseMove 和OnMouseLeave 中检测到热跟踪的变化。在那里我们设置了HotTrackedIndex。这是一个在必要时触发绘图的属性。
在OnGotFocus 和OnLostFocus 中,我们刷新所选项目以根据焦点状态更改其颜色。
我的颜色与您的图片不匹配,但您可以轻松调整它们。如果您需要创建非标准颜色的画笔和钢笔,请将它们创建为静态和只读的,或者不要忘记处理它们。
private static readonly Brush HotTrackBrush = new SolidBrush(new Color(123, 45, 67));
private static readonly Pen HotTrackPen = new Pen(new Color(234, 56, 78));
此列表框的改进版本可以将不同的选择和热跟踪颜色显示为属性,以便您可以在属性窗口中轻松更改它们。 (属性会自动出现在那里。)