WinForms C#中OnDrawItem无法覆盖CheckedListBox高亮颜色的问题
解决CheckedListBox选中高亮无法覆盖的问题
问题分析
你当前的代码先调用了e.DrawBackground(),这会优先绘制系统默认的蓝色选中高亮,之后再填充自定义颜色的矩形,导致默认高亮无法被完全覆盖。同时传递给基类的参数处理逻辑也需要调整。
解决方案
1. 完全禁用选中高亮效果
直接跳过默认背景绘制,自行控制所有背景渲染,同时移除传递给基类参数的选中状态:
protected override void OnDrawItem(DrawItemEventArgs e) { this.CheckOnClick = true; // 绘制默认背景色,完全替代系统默认高亮逻辑 using (Brush brush = new SolidBrush(e.BackColor)) { e.Graphics.FillRectangle(brush, e.Bounds); } // 构造移除选中状态的参数,让基类不绘制默认高亮 DrawItemEventArgs e2 = new DrawItemEventArgs( e.Graphics, e.Font, e.Bounds, e.Index, e.State & ~DrawItemState.Selected, e.ForeColor, e.BackColor ); base.OnDrawItem(e2); // 按需保留焦点框绘制 if ((e.State & DrawItemState.Focus) == DrawItemState.Focus) { e.DrawFocusRectangle(); } }
2. 彻底覆盖选中高亮颜色
调整绘制顺序,先绘制自定义选中背景,再让基类绘制内容,确保自定义颜色完全覆盖默认高亮:
protected override void OnDrawItem(DrawItemEventArgs e) { this.CheckOnClick = true; // 区分选中/未选中状态,绘制自定义背景 if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { // 自定义选中背景色 using (Brush brush = new SolidBrush(Color.FromArgb(40, 40, 40))) { e.Graphics.FillRectangle(brush, e.Bounds); } } else { // 非选中项使用默认背景 using (Brush brush = new SolidBrush(e.BackColor)) { e.Graphics.FillRectangle(brush, e.Bounds); } } // 移除选中状态参数,避免基类绘制默认蓝色高亮 DrawItemEventArgs e2 = new DrawItemEventArgs( e.Graphics, e.Font, e.Bounds, e.Index, e.State & ~DrawItemState.Selected, e.ForeColor, e.BackColor ); base.OnDrawItem(e2); // 按需绘制焦点框 if ((e.State & DrawItemState.Focus) == DrawItemState.Focus) { e.DrawFocusRectangle(); } }
关键说明
- 核心是不要调用
e.DrawBackground(),这个方法会直接绘制系统默认的选中高亮,后续自定义绘制无法完全覆盖它。 - 通过
e.State & ~DrawItemState.Selected移除选中状态后,基类的OnDrawItem不会再触发默认蓝色高亮的绘制,确保自定义背景完全生效。
内容的提问来源于stack exchange,提问作者Marcel Majhenic
相关产品推荐
相关产品推荐

