I need to show items in a combobox with a different background color. I also want to change what that color is depending on if the item is selected (or the mouse is on top of it), just the same way it works when a combobox is not owner-drawn.
It is all working fine, except that when the mouse comes off one of the items that I changed the color for, the item keeps the same color as when the mouse was on top. In the example below, the item 'other' is initially correctly drawn with myUnselectedBrush; the mouse goes over top, it is correctly drawn with mySelectedBrush; when the mouse comes off, it is incorrectly still drawn with mySelectedBrush; it should have been drawn with myUnselectedBrush. Everything works fine for item 'something', whose color is not altered.
What am I doing wrong?
private void comboBoxDraw(object sender, DrawItemEventArgs e)
{
ComboBox cb = (ComboBox)sender;
Graphics g = e.Graphics;
e.DrawBackground();
if (e.Index > -1)
{
object item = cb.Items[e.Index];
switch (somethingOrOther)
{
case something:
break;
case other:
e.Graphics.FillRectangle(
(cb.SelectedIndex == e.Index)
? mySelectedBrush
: myUnselectedBrush,
e.Bounds);
break;
}
}
}
e.DrawFocusRectangle();
if (e.Index > -1)
{
// draw the string
}
}