2014-12-22 225 views
1

當我將鼠標懸停在列表框項目上時,如何更改列表框項目的背景顏色?
我已重寫DrawItem事件與此代碼:如何在懸停時更改ListBox項目的背景顏色?

private void DrawListBox(object sender, DrawItemEventArgs e) 
{ 
    e.DrawBackground();   
    Graphics g = e.Graphics; 
    Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? 
     new SolidBrush(Color.FromArgb(52, 146, 204)) : new SolidBrush(e.BackColor); 
    g.FillRectangle(brush, e.Bounds); 

    e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, 
     new SolidBrush(e.ForeColor), e.Bounds, StringFormat.GenericDefault); 
    e.DrawFocusRectangle(); 
} 

然而,列表框沒有包含懸停項的屬性。也沒有像MouseEnterItem,MouseHoverItem事件或任何類似ListBox上訂閱的事件。

我做了很多的研究,但我發現在SO類似的問題,這困惑的ListBox和ListView:Hightlight Listbox item on mouse over event

回答

2

與列表框不提供MouseEnterItem和MouseHoverItem活動,有必要自己編寫此功能,跟蹤鼠標的座標以確定鼠標結束了哪個項目。

下面的問題非常相似,目的是在展開每個項目時展示工具提示。麥郎的回答是一個很好的解決辦法,應該爲您的目的是適應性強:

How can I set different Tooltip text for each item in a listbox?

1

你真的想要一個懸停? =>用戶移動鼠標,然後在對延遲的點。如果你想即時反饋,然後使用鼠標移動()事件,並獲得該項目的指標你是在與IndexFromPoint()停止,而無需再次移動

。將該值存儲在表單級別,以便確定自上次移動以來是否發生了更改,然後在DrawListBox()處理函數中相應地設置背景填充顏色:

private int prevIndex = -1; 

    private void listBox1_MouseMove(object sender, MouseEventArgs e) 
    { 
     int index = listBox1.IndexFromPoint(listBox1.PointToClient(Cursor.Position)); 
     if (index != prevIndex) 
     { 
      prevIndex = index; 
      listBox1.Invalidate(); 
     } 
    } 

    private void listBox1_MouseLeave(object sender, EventArgs e) 
    { 
     prevIndex = -1; 
     listBox1.Invalidate(); 
    } 

    private void DrawListBox(object sender, DrawItemEventArgs e) 
    { 
     e.DrawBackground(); 
     Graphics g = e.Graphics; 

     Color c; 
     if (e.Index == prevIndex) 
     { 
      c = Color.Yellow; // whatever the "highlight" color should be 
     } 
     else if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
     { 
      c = Color.FromArgb(52, 146, 204); 
     } 
     else 
     { 
      c = e.BackColor; 
     } 
     using (SolidBrush brsh = new SolidBrush(c)) 
     { 
      g.FillRectangle(brsh, e.Bounds); 
     } 

     using (SolidBrush brsh = new SolidBrush(e.ForeColor)) 
     { 
      g.DrawString(listBox1.Items[e.Index].ToString(), e.Font, 
      brsh, e.Bounds, StringFormat.GenericDefault); 
     } 

     e.DrawFocusRectangle(); 
    } 
相關問題