Changing the Color of ComboBox highlighting

后端 未结 1 1448
孤街浪徒
孤街浪徒 2021-01-04 07:30

I am trying to work around changing the color of highlighting in a ComboBox dropdown on a C# Windows Forms application. I have searched the whole w

1条回答
  •  借酒劲吻你
    2021-01-04 08:21

    In case you are using the ComboBox in more than one place in your project, it will not make sense to repeat the same code for DrawItem event over and over again. Just add this class to your project and you will have a new ComboBox control that has the HightlightColor property which will makes it easier to use the control all over the project:

    class AdvancedComboBox : ComboBox
    {
        new public System.Windows.Forms.DrawMode DrawMode { get; set; }
        public Color HighlightColor { get; set; }
    
        public AdvancedComboBox()
        {
            base.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.HighlightColor = Color.Gray;
            this.DrawItem += new DrawItemEventHandler(AdvancedComboBox_DrawItem);
        }
    
        void AdvancedComboBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
                return;
    
            ComboBox combo = sender as ComboBox;
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                e.Graphics.FillRectangle(new SolidBrush(HighlightColor),
                                         e.Bounds);
            else
                e.Graphics.FillRectangle(new SolidBrush(combo.BackColor),
                                         e.Bounds);
    
            e.Graphics.DrawString(combo.Items[e.Index].ToString(), e.Font,
                                  new SolidBrush(combo.ForeColor),
                                  new Point(e.Bounds.X, e.Bounds.Y));
    
            e.DrawFocusRectangle();
        }
    }
    

    0 讨论(0)
提交回复
热议问题