重绘所有者绘制的Winforms组合框项目 [英] Redrawing of owner-drawn winforms combobox items

查看:95
本文介绍了重绘所有者绘制的Winforms组合框项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在具有不同背景颜色的组合框中显示项目.我还想更改颜色,具体取决于是否选中了该项目(或鼠标位于其上方),就像在没有所有者绘制组合框的情况下一样.

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.

一切正常,只是当鼠标移开我为其更改颜色的项目之一时,该项目保持与鼠标在顶部相同的颜色.在下面的示例中,最初使用myUnselectedBrush正确绘制了其他"项;鼠标移到顶部,可以使用mySelectedBrush正确绘制;当鼠标移开时,仍会用mySelectedBrush错误地绘制鼠标;它应该已经用myUnselectedBrush绘制了.一切都适用于颜色不变的项目某物".

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.

我在做什么错了?

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

推荐答案

而不是使用

cb.SelectedIndex == e.Index

我需要使用DrawItemState:

I needed to use DrawItemState:

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

这篇关于重绘所有者绘制的Winforms组合框项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆