更改WinForms组合框的选择颜色 [英] Change the Selection Color of a WinForms ComboBox

查看:134
本文介绍了更改WinForms组合框的选择颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有,我有一个深入的看,但似乎找不到我要找的。我想要改变一个ComboBoc控件的选择颜色(理想情况下,不必子类的控制)。我虽然做下面的工作,但这个事件甚至不会启动

All, I have had an indepth look but can't seem to find what I am looking for. I want ot change the selection color of a ComboBoc control (ideally without having to sub-class the control). I though doing the following would work, but this event is not even firing

private void comboBoxDb_DrawItem(object sender, DrawItemEventArgs e) 
{
    ComboBox combo = sender as ComboBox;
    e.Graphics.FillRectangle(new SolidBrush(combo.BackColor), e.Bounds);
    string strSelectionColor = @"#99D4FC";
    Color selectionColor = 
        System.Drawing.ColorTranslator.FromHtml(strSelectionColor);
    e.Graphics.DrawString(combo.Items[e.Index].ToString(), 
                          e.Font, 
                          new SolidBrush(selectionColor), 
                          new Point(e.Bounds.X, e.Bounds.Y));
}

但这个事件甚至没有触发。我在这里做错了什么?

but this event is not even firing. What am I doing wrong here?

感谢您的时间。

虽然非触发是由于没有设置由@Teppic正确指出的ComboBox的DrawMode属性,但是这仍然没有做我需要的。我想设置选择颜色,我上面做了(我已经在这里阻止了名称)

而我想改变蓝色高亮控制,如下所示

推荐答案

将ComboBox控件的DrawMode属性设置为OwnerDrawFixed(如果每个项目的高度相同)或OwnerDrawVariable (如果每个项目的高度可能不同)。

Set the DrawMode property of the ComboBox control to either OwnerDrawFixed (if the height of each item will be the same) or OwnerDrawVariable (if the height of each item may vary).

然后将您的DrawItem事件修改为类似以下内容(明显替换您自己的颜色):

Then modify your DrawItem event to something like the following (substitute your own colours in obviously):

private void comboBoxDb_DrawItem(object sender, DrawItemEventArgs e) 
{
    var combo = sender as ComboBox;

    if((e.State & DrawItemState.Selected) == DrawItemState.Selected)
    {
        e.Graphics.FillRectangle(new SolidBrush(Color.BlueViolet), e.Bounds);
    }
    else
    {
        e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window), e.Bounds);
    }

    e.Graphics.DrawString(combo.Items[e.Index].ToString(),
                                  e.Font,
                                  new SolidBrush(Color.Black),
                                  new Point(e.Bounds.X, e.Bounds.Y));
}

这篇关于更改WinForms组合框的选择颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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