如何在单击项目时删除包装listBox1中所选项目的蓝色?

时间:2014-05-19 16:12:19

标签: c# winforms

当我点击listBox1选择一个项目时,该项目会以蓝色围绕它。我怎样才能删除这种颜色?

enter image description here

2 个答案:

答案 0 :(得分:4)

使用此代码将选择颜色更改为您想要的任何颜色:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        //Add this to your form initialization
        this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
    }

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index < 0) return;
        //if the item state is selected them change the back color 
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            e = new DrawItemEventArgs(e.Graphics,
                                      e.Font,
                                      e.Bounds,
                                      e.Index,
                                      e.State ^ DrawItemState.Selected,
                                      e.ForeColor,
                                      Color.Transparent);//Choose the color

        // Draw the background of the ListBox control for each item.
        e.DrawBackground();
        // Draw the current item text
        e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
        // If the ListBox has focus, draw a focus rectangle around the selected item.
        e.DrawFocusRectangle();
    }
}

我使用透明颜色来删除选择的背景颜色,但如果您想要任何其他颜色,只需自行更改。
我将此答案用作帮助:How to change ListBox selection background color?

在表单上显示:

ListBox Form

如果要取消选择列表框中的项目,请使用

listBox1.ClearSelected();

listBox1.SelectedIndex = -1;

干杯!

答案 1 :(得分:1)

对于ListBox,您可以编写如下代码:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string s = string.Empty;

    if (listBox1.SelectedIndex != -1) 
        s = listBox1.SelectedItem.ToString();

    /// continue you code here .... 
    /// 

    /// after that remove the hilight 

    listBox1.SelectedIndex = -1;
}