它一般工作,但是因爲我想讓它的顏色只在右鍵點擊鼠標右鍵時才顯示,因爲當我顯示/打開列表框時它首先要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現在是第一次。
編輯:
我需要兩件事。
- 單擊項目上的鼠標左鍵時,它會像以前一樣標有常規藍色。
- 當在一個物品上點擊鼠標右鍵時,它會被塗成紅色。
- 要啓用多個chocies,所以如果我點擊鼠標右鍵,它會保持已經在紅色的其他項目,所以我可以選擇許多項目在紅色。
不是DrawItem爲列表中的每個項目運行嗎?你需要捕捉點擊的物品,並有邏輯檢查當前正在繪製的物品是否與點擊的物品相同... –