Combobox draw image on selected

天涯浪子 提交于 2019-11-28 14:49:50

Change you ComboBox DrawMode to OwnerDrawVariable.
Use the DrawItem event to draw the images from your source (an ImageList, in this case) inside the ComboBox item Bounds.

If the ComboBox DropDownStyle is set to DropDownList, the image will be shown in the selection box; if it's set to DropDown, only the text will be drawn.

Here, the Focus rectangle is only drawn when the mouse point hovers the ListControl's items, while it's not used when an item is selected, which is determined by:
(e.State.HasFlag(DrawItemState.Focus) && !e.State.HasFlag(DrawItemState.ComboBoxEdit)).

// These could be properties used to customize the ComboBox appearance
Color cboForeColor = Color.Black;
Color cboBackColor = Color.WhiteSmoke;

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index < 0) return;
    Color foreColor = e.ForeColor;
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

    if (e.State.HasFlag(DrawItemState.Focus) && !e.State.HasFlag(DrawItemState.ComboBoxEdit)) {
        e.DrawBackground();
        e.DrawFocusRectangle();
    }
    else {
        using (Brush backgbrush = new SolidBrush(cboBackColor)) {
            e.Graphics.FillRectangle(backgbrush, e.Bounds);
            foreColor = cboForeColor;
        }
    }
    using (Brush textbrush = new SolidBrush(foreColor)) {
        e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(),
                              e.Font, textbrush, e.Bounds.Height + 10, e.Bounds.Y,
                              StringFormat.GenericTypographic);
    }
    e.Graphics.DrawImage(this.imageList1.Images[e.Index],
                         new Rectangle(e.Bounds.Location,
                         new Size(e.Bounds.Height - 2, e.Bounds.Height - 2)));
}

The Magic Numbers here (10, -2) are just offsets:
e.Bounds.Height + 10 => 10 pixels to the right of the image.
e.Bounds.Height -2 => 2 pixels less than the item.Bounds.Height.

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