How to change ListBox selection background color?

后端 未结 5 1426
执念已碎
执念已碎 2020-11-28 12:49

It seems to use default color from Windows settings which is blue by default. Let\'s say I want to change it to red permanently. I\'m using Winforms.

Thanks in advan

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 13:24

    The below code does exactly what you are saying:

    In the InitializeComponent method:

    this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;
    this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(listBox1_DrawItem);
    this.listBox1.SelectedIndexChanged += new System.EventHandler(listBox1_SelectedIndexChanged);
    

    And the event handlers:

    void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        this.listBox1.Invalidate();
    }
    
    void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
    {
        int index = e.Index;
        Graphics g = e.Graphics;
        foreach (int selectedIndex in this.listBox1.SelectedIndices)
        {
            if (index == selectedIndex)
            {
                // Draw the new background colour
                e.DrawBackground();
                g.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
            }
        }
    
        // Get the item details
        Font font = listBox1.Font;
        Color colour = listBox1.ForeColor;
        string text = listBox1.Items[index].ToString();
    
        // Print the text
        g.DrawString(text, font, new SolidBrush(Color.Black), (float)e.Bounds.X, (float)e.Bounds.Y);
        e.DrawFocusRectangle();
    }
    

    Code is taken from:

    http://www.weask.us/entry/change-listbox-rsquo-selected-item-backcolor-net

提交回复
热议问题