public partial class ColorComboBox : ComboBox
{
private System.ComponentModel.IContainer components = null;
public Pen RectangleBorderColor { get; set; }
public Color RectangleFillColor { get; set; }
public int RectangleWidth { get; set; }
public int RectangleHeight { get; set; }
public int RectangleXOffset { get; set; }
public int RectangleYOffset { get; set; }
public int TextXOffset { get; set; }
public int TextYOffset { get; set; }
public ColorComboBox()
{
InitializeComponent();
RectangleBorderColor = Pens.Black;
RectangleFillColor = Color.White;
RectangleHeight = this.Height / 2;
RectangleWidth = RectangleHeight;
RectangleXOffset = this.Width % RectangleWidth;
RectangleYOffset = this.Height % RectangleHeight;
TextXOffset = RectangleWidth / 2;
TextYOffset = 0;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components
= new System.ComponentModel.Container(); }
protected override void OnCreateControl()
{
base.OnCreateControl();
this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.DrawBackground();
if (e.Index > -1)
{
object obj = this.Items[e.Index];
object objValue = obj.GetType().GetProperty(this.ValueMember).GetGetMethod().Invoke(obj, null);
string dispalyMember = obj.GetType().GetProperty(this.DisplayMember).GetValue(obj, null).ToString();
Color fillColor
= objValue
is Color
? (Color
)objValue
: RectangleFillColor
;
int width = RectangleWidth > e.Bounds.Width ? e.Bounds.Width : RectangleWidth;
int height = RectangleHeight > e.Bounds.Height ? e.Bounds.Height : RectangleHeight;
int xOffset = RectangleXOffset > e.Bounds.Width - width ? e.Bounds.Width - width : RectangleXOffset;
int yOffset = RectangleYOffset > e.Bounds.Height - height ? e.Bounds.Height - height : RectangleYOffset;
Rectangle colorRectangle
= new Rectangle
(e
.Bounds.X + xOffset, e
.Bounds.Y + yOffset, width, height
);
using (Brush brush
= new SolidBrush
(fillColor
)) {
e.Graphics.FillRectangle(brush, colorRectangle);
e.Graphics.DrawRectangle(Pens.Black, colorRectangle);
}
using (Brush brush
= new SolidBrush
(e
.ForeColor)) {
e.Graphics.DrawString(dispalyMember, e.Font, brush, colorRectangle.Right + TextXOffset, e.Bounds.Top + TextYOffset);
}
e.DrawFocusRectangle();
}
}
}