How do I change the Background Color of a ListBox Item when I hover over it?
I have overridden the DrawItem Event with this code:
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();
}
However, a ListBox does not have a Property which contains the hovered Item. There is also no Event like MouseEnterItem, MouseHoverItem Event, or anything similar on a ListBox to subscribe to.
I did quite a lot of research, but all I found was a similar question on SO, which confused ListBox and ListView: Hightlight Listbox item on mouse over event
As the ListBox does not provide the MouseEnterItem and MouseHoverItem Events, it is necessary to code this functionality yourself, tracking the coordinates of the mouse to determine which item the mouse is over.
The following question is very similar, aimed at showing a tooltip for each item when hovered over. Michael Lang's answer is a very good workaround and should be adaptable for your purposes:
How can I set different Tooltip text for each item in a listbox?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments