2012-12-28 34 views
0

它一般工作,但是因爲我想讓它的顏色只在右鍵點擊鼠標右鍵時才顯示,因爲當我顯示/打開列表框時它首先要DrawItem事件:我如何爲列表框中的選定項目着色?在點擊鼠標右鍵時只着色選定的項目文本

private void listBox1_MouseDown(object sender, MouseEventArgs e) 
     { 
      listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y); 

      if (e.Button == System.Windows.Forms.MouseButtons.Right) 
      { 
       isColor = true; 
      } 
     } 

     private void listBox1_DrawItem(object sender, DrawItemEventArgs e) 
     { 
      if (isColor == true) 
      { 
       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.Red);//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(); 
      } 
     } 

我用一個標誌isColor但因爲它是第一個要DrawItem事件這個代碼不工作良好。 由於isColor現在是第一次。

編輯:

我需要兩件事。

  1. 單擊項目上的鼠標左鍵時,它會像以前一樣標有常規藍色。
  2. 當在一個物品上點擊鼠標右鍵時,它會被塗成紅色。
  3. 要啓用多個chocies,所以如果我點擊鼠標右鍵,它會保持已經在紅色的其他項目,所以我可以選擇許多項目在紅色。
+0

不是DrawItem爲列表中的每個項目運行嗎?你需要捕捉點擊的物品,並有邏輯檢查當前正在繪製的物品是否與點擊的物品相同... –

回答

0

爲列表中的每個項目調用OnDrawItem。你正在爲每個項目着色紅色。你需要檢查,看看是否需要繪製的產品所選擇的項目(如果我沒記錯的話,這將是e.Selected),如果是那麼它顏色紅色,否則顏色別的東西..也許SystemColors.Window

+0

更新了我的問題。 – user1196715

0

試試這個:

if(((ListBox)sender).SelectedIndex == e.index) 
{ 
.... 
} 
+0

keyboardP dupilcated鏈接示例正在工作。問題是我只想在用戶用鼠標右鍵點擊一個項目時給每個項目上色。所以我試圖使用一個標誌,但問題是,當我顯示/打開列表框,它首先進入DrawItem事件。我只是用它更新了我的問題。 – user1196715

相關問題