2010-10-01 59 views
0

所以我有这个代码来改变列表框项目的背景选择颜色为默认的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(); 

这工作正常,但我也想改变所选项目的字体颜色。我该怎么做?

回答

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(); 
+0

刷子需要被设置,你还有绘制背景如果index <0. – 2010-10-01 14:16:34

+0

@Hans:处置的System.Drawing.Brushes(只读静态对象)中的一个是一个好主意。因为WM_ERASEBKGND会照顾它,所以如果它与控件的BackColor(即WNDCLASS.hbrBackground)不同,则只需绘制背景。 – Tergiver 2010-10-01 14:39:41

+0

是的,好点。 – 2010-10-01 14:44:02

0

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