前景列表框颜色

时间:2010-10-01 12:23:27

标签: c# winforms

所以我有这个代码在默认的Winforms中将列表框项目的背景选择颜色更改为红色。

if (e.Index < 0) return;
            // if the item state is selected then 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.Red); // Choose the color

            // Draw the background of the ListBox control for each item.
            e.DrawBackground();
            // Draw the current item text
            e.Graphics.DrawString(studentsListBox.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();

这很好但我也想更改所选项目的字体颜色。我该怎么做?

2 个答案:

答案 0 :(得分:1)

if (e.Index < 0)
    return;

Brush foreBrush = Brushes.Black; // non-selected text color
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
    foreBrush = Brushes.White; // selected text color
    e = new DrawItemEventArgs(e.Graphics,
                              e.Font,
                              e.Bounds,
                              e.Index,
                              e.State ^ DrawItemState.Selected,
                              e.ForeColor,
                              Color.Red); // Choose the color 
}

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

答案 1 :(得分:0)

你不能只提供e.ForeColor以外的颜色吗?