Redrawing of owner-drawn winforms combobox items

荒凉一梦 提交于 2019-12-13 04:05:48

问题


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
    }
}

回答1:


Rather than using

cb.SelectedIndex == e.Index

I needed to use DrawItemState:

((state & DrawItemState.Selected) > 0) || ((state & DrawItemState.HotLight) > 0)


来源:https://stackoverflow.com/questions/12123015/redrawing-of-owner-drawn-winforms-combobox-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!