在Winforms中更改ListBox的"选定"颜色?

Ozt*_*aco 3 c# listbox winforms

当你listbox在Windows窗体中选择某些东西时,你如何改变那种丑陋的蓝色?我能找到的所有解决方案都包括重新创建整个控件,或者只使用WPF.在WinForms中有没有办法做到这一点?

Ser*_*kiy 12

DrawModelistBox设置为OwnerDrawFixed并订阅DrawItem事件:

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    Graphics g = e.Graphics;
    Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? 
                  Brushes.Red : new SolidBrush(e.BackColor);
    g.FillRectangle(brush, e.Bounds);
    e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, 
             new SolidBrush(e.ForeColor), e.Bounds, StringFormat.GenericDefault); 
    e.DrawFocusRectangle();            
}
Run Code Online (Sandbox Code Playgroud)

您可以通过检查e.State事件参数的属性来确定绘图项的状态.如果状态是Selected,则使用您喜欢的任何刷子(例如红色)来填充项目线.