changing selected itms color in a listbox

后端 未结 2 1000
暗喜
暗喜 2021-01-25 18:43

i want to change the color of a selected items from a list box control how to do that in windows(Winforms)

2条回答
  •  无人及你
    2021-01-25 19:19

    As far as I know if you want to do that you need to make the ListBox.DrawMode OwnerDrawFixed and add an event handler on to the DrawItem method.

    Something like this might do what you want:

        private void lstDrawItem(object sender, DrawItemEventArgs e)
        {
            ListBox lst = (ListBox)sender;
            e.DrawBackground();
            e.DrawFocusRectangle();
    
            DrawItemState st = DrawItemState.Selected ^ DrawItemState.Focus;
            Color col = ((e.State & st) == st) ? Color.Yellow : lst.BackColor;
    
            e.Graphics.DrawRectangle(new Pen(col), e.Bounds);
            e.Graphics.FillRectangle(new SolidBrush(col), e.Bounds);
            if (e.Index >= 0)
            {
                e.Graphics.DrawString(lst.Items[e.Index].ToString(), e.Font, new SolidBrush(lst.ForeColor), e.Bounds, StringFormat.GenericDefault);
            }
        }
    

    Hope it helps James

提交回复
热议问题