在 Windows 7 上运行的 winform 应用程序中,我希望更改组合框的背景颜色以突出显示它。 组合框的 DropDownStyle 为 DropDownList。
当我以编程方式将 BackColor 属性更改为红色时,只有实际下拉列表的背景更改为红色。当下拉列表未打开时,显示所选值的组合框背景保持灰色。我该怎么办才能让它也变红?
当应用程序在 Windows XP 上运行时,设置 BackColor 属性效果很好
这应该可以帮助您开始。
将组合框的DrawMode属性更改为OwnerDrawFixed,并处理DrawItem事件:
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
int index = e.Index >= 0 ? e.Index : 0;
var brush = Brushes.Black;
e.DrawBackground();
e.Graphics.DrawString(comboBox1.Items[index].ToString(), e.Font, brush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
背景颜色将是正确的,但盒子的样式将是平面的,而不是通常的3D样式。
由于使用 Igby Largeman 的解决方案无论如何都会失去 3D 效果,因此最好将
FlatStyle
属性更改为 Flat
。即使在 Windows 7 中,背景颜色似乎也是如此,并且无需重新实现任何低级事件。
我认为这是微软的一个错误......
Igby Largeman 的回答让我完成了 95% 的任务。并归功于 Sasha Bond 的画笔着色,用于在选择时设置突出显示文本颜色。
为了达到 100%,我所做的一些改进是从 ComboBox 的 ForeColor 添加画笔颜色,并在索引为 -1 时进行处理(并将其设置为 -1 开始,这样它的行为与正常的 dropdownstyle ComboBox 完全相同)。
最重要的是,当将其设置回标准下拉样式时,它仍然表现正常。
private void comboBox1_DrawItem ( object sender, DrawItemEventArgs e )
{
int index = e.Index >= 0 ? e.Index : -1;
Brush brush = ( ( e.State & DrawItemState.Selected ) > 0 ) ? SystemBrushes.HighlightText : new SolidBrush ( comboBox1.ForeColor );
e.DrawBackground ();
if ( index != -1 )
{
e.Graphics.DrawString ( comboBox1.Items[index].ToString (), e.Font, brush, e.Bounds, StringFormat.GenericDefault );
}
e.DrawFocusRectangle ();
}
这是我为另一个可能感兴趣的初学者在 vb 项目中使用的内容。可以使用事件的发送者作为触发该事件的组合框。通过强制转换,您可以访问列表的元素。我还更改了图形 TextRenderingHint 以实现更好的字体显示。
Private Sub PaintComboBoxItem(sender As Object, e As DrawItemEventArgs)
Dim combobox As ComboBox = sender
Dim index As Integer = If(e.Index >= 0, e.Index, 0)
Dim brush As Brush = If(combobox.Enabled,
New SolidBrush(m_UITheme.TitleColor),
New SolidBrush(m_UITheme.White))
e.Graphics.SmoothingMode = SmoothingMode.HighQuality
e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit
e.DrawBackground()
e.Graphics.DrawString(combobox.Items(index).ToString(), combobox.Font, brush, e.Bounds, StringFormat.GenericDefault)
e.DrawFocusRectangle()
End Sub
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
var cmb = (ComboBox) sender;
if (cmb == null) return;
if (e.Index % 2 == 0)
{
e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);
e.Graphics.DrawString(cmb.Items[e.Index].ToString(), cmb.Font, SystemBrushes.GrayText, e.Bounds);
}
else
{
e.DrawBackground();
// change background color
e.Graphics.FillRectangle(Brushes.AntiqueWhite, e.Bounds);
// change foreground color
Brush brush = ((e.State & DrawItemState.Selected) > 0) ? SystemBrushes.HighlightText : SystemBrushes.ControlText;
e.Graphics.DrawString(cmb.Items[e.Index].ToString(), cmb.Font, brush, e.Bounds);
e.DrawFocusRectangle();
}
}
您应该将焦点移动到组合框 selectedIndexChange 事件函数中的另一个控件。