修改ComboBox下拉列表的边框颜色
修改ComboBox下拉列表的边框颜色
我懂你现在的困扰——虽然已经自定义绘制了ComboBox的下拉项,但那个默认的蓝色边框还是顽固地留在那里对吧?其实只要在你的DrawItem事件处理代码里加上几行自定义边框绘制的逻辑,就能把它替换成你想要的颜色了。
问题原因
那个蓝色边框是系统默认绘制的下拉项边框,咱们需要手动绘制自己的边框来覆盖它,才能完全自定义样式。
修改后的完整代码
Private Sub ComboBox2_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ComboBox2.DrawItem If e.Index < 0 Then Return e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias Dim CB As ComboBox = TryCast(sender, ComboBox) Dim itemBounds As Rectangle = e.Bounds ' 自定义边框和背景颜色 Dim borderColor As Color = If((e.State And DrawItemState.Selected) = DrawItemState.Selected, Color.White, Color.DarkRed) Dim backColor As Color = If((e.State And DrawItemState.Selected) = DrawItemState.Selected, Color.DarkRed, CB.BackColor) ' 填充项背景 e.Graphics.FillRectangle(New SolidBrush(backColor), itemBounds) ' 绘制项文本(调整偏移量让文本不贴边框) e.Graphics.DrawString(CB.Items(e.Index).ToString(), e.Font, New SolidBrush(CB.ForeColor), New Point(itemBounds.X + 2, itemBounds.Y + 2)) ' 绘制自定义边框,替换系统蓝色边框 e.Graphics.DrawRectangle(New Pen(borderColor), itemBounds.X, itemBounds.Y, itemBounds.Width - 1, itemBounds.Height - 1) ' 可选:保留焦点矩形,提升 accessibility If (e.State And DrawItemState.Focus) = DrawItemState.Focus Then e.DrawFocusRectangle() End If End Sub
关键说明
- 边框颜色控制:我这里设置选中项用白色边框(和深红背景形成对比),未选中项用深红边框,你可以根据需求替换成任意颜色
- 边框绘制范围:用
itemBounds.Width - 1和itemBounds.Height - 1是为了让边框刚好贴合项的区域,避免超出范围 - 文本偏移:给文本加了
+2的偏移,避免文本紧贴边框,视觉效果更舒服 - 必要前提:请确保你的ComboBox控件的
DrawMode属性已经设置为OwnerDrawFixed或者OwnerDrawVariable,否则DrawItem事件不会被触发
内容的提问来源于stack exchange,提问作者Sérgio Jesus




