如何修改Windows Forms中CheckListbox的高亮颜色
修改Windows Forms CheckListBox高亮颜色的实现方法
原生Windows Forms的CheckedListBox没有直接提供修改高亮颜色的属性,需要通过自定义控件并重写绘制方法来实现,具体步骤如下:
1. 创建自定义CheckedListBox控件
继承自CheckedListBox,重写OnDrawItem方法手动绘制项的外观,包括高亮状态的颜色:
using System.Drawing; using System.Windows.Forms; public class CustomCheckedListBox : CheckedListBox { // 可自定义的高亮背景色,默认浅蓝色 public Color HighlightBackColor { get; set; } = Color.LightBlue; // 可自定义的高亮文字颜色,默认黑色 public Color HighlightForeColor { get; set; } = Color.Black; public CustomCheckedListBox() { // 必须设置为OwnerDrawFixed才能手动绘制 DrawMode = DrawMode.OwnerDrawFixed; } protected override void OnDrawItem(DrawItemEventArgs e) { // 处理无效索引 if (e.Index < 0 || e.Index >= Items.Count) { base.OnDrawItem(e); return; } bool isChecked = GetItemChecked(e.Index); bool isHighlighted = (e.State & DrawItemState.Selected) == DrawItemState.Selected; // 确定背景和文字颜色 Color bgColor = isHighlighted ? HighlightBackColor : BackColor; Color textColor = isHighlighted ? HighlightForeColor : ForeColor; // 填充背景 using (SolidBrush bgBrush = new SolidBrush(bgColor)) { e.Graphics.FillRectangle(bgBrush, e.Bounds); } // 绘制复选框 var glyphSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal); var checkBoxPos = new Point( e.Bounds.Left, e.Bounds.Top + (e.Bounds.Height - glyphSize.Height) / 2 ); var checkState = isChecked ? System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal : System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal; CheckBoxRenderer.DrawCheckBox(e.Graphics, checkBoxPos, checkState); // 绘制文本,偏移复选框宽度 using (SolidBrush textBrush = new SolidBrush(textColor)) { var textPos = new Point( e.Bounds.Left + 20, e.Bounds.Top + (e.Bounds.Height - e.Font.Height) / 2 ); e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, textBrush, textPos); } // 绘制焦点框(如果有焦点) if ((e.State & DrawItemState.Focus) == DrawItemState.Focus) { e.DrawFocusRectangle(); } } }
2. 使用自定义控件
- 编译项目后,
CustomCheckedListBox会自动出现在Visual Studio的工具箱中,直接拖到窗体上即可使用 - 在属性窗口中找到
HighlightBackColor和HighlightForeColor,可以直接设置想要的颜色 - 也可以通过代码动态修改:
// 示例:设置高亮背景为深橙色,文字为白色 customCheckedListBox1.HighlightBackColor = Color.DarkOrange; customCheckedListBox1.HighlightForeColor = Color.White;
注意事项
- 如果需要支持不同高度的列表项,可以将
DrawMode设置为OwnerDrawVariable,并重写OnMeasureItem方法来指定每个项的高度 - 若要处理禁用项的样式,可在
OnDrawItem中添加对应的状态判断和绘制逻辑
内容的提问来源于stack exchange,提问作者Marcel Majhenic
相关产品推荐
相关产品推荐

