2010-10-01 62 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以外的顏色嗎?