How to change ForeColor of SelectedItem in ListBox

寵の児 提交于 2019-12-06 00:20:37

You can set DrawMode property of ListBox to OwnerDrawFixed and then hanlde DrawItem event of the control and draw items yourself:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var listBox = sender as ListBox;
    var backColor = this.BackColor;         /*Default BackColor*/
    var textColor = this.ForeColor;         /*Default ForeColor*/
    var txt = listBox.GetItemText(listBox.Items[e.Index]);
    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
    {
        backColor = Color.RoyalBlue;        /*Seletion BackColor*/
        textColor = Color.Yellow;           /*Seletion ForeColor*/
    }
    using (var brush = new SolidBrush(backColor))
        e.Graphics.FillRectangle(brush, e.Bounds);
    TextRenderer.DrawText(e.Graphics, txt, listBox.Font, e.Bounds, textColor,
        TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!