Here you go:
public class myCombo : ComboBox
{
// expose properties as needed
public Color SelectedBackColor{ get; set; }
// constructor
public myCombo()
{
DrawItem += new DrawItemEventHandler(DrawCustomMenuItem);
DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
SelectedBackColor= Color.LightSeaGreen;
}
protected void DrawCustomMenuItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
// a dropdownlist may initially have no item selected, so skip the highlighting:
if (e.Index >= 0)
{
Graphics g = e.Graphics;
Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ?
new SolidBrush(SelectedBackColor) : new SolidBrush(e.BackColor);
Brush tBrush = new SolidBrush(e.ForeColor);
g.FillRectangle(brush, e.Bounds);
e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font,
tBrush, e.Bounds, StringFormat.GenericDefault);
brush.Dispose();
tBrush.Dispose();
}
e.DrawFocusRectangle();
}
}
You may consider exposing more Properties as you expand your customziation, so you can change them for each instance when you want to..
Also don't forget to dispose GDI objects you create, like brushes and pens!
Edit: Just noticed that BackColor
would hide the original property. Changed it to SelectedBackColor
, which actually says what it is!
Edit 2: As Simon noted in the comments, there is a HasFlag
method and so as of .Net 4.0 one can also write:
Brush brush = ((e.State.HasFlag(DrawItemState.Selected) ?
which is a little clearer and shorter.
Edit 3: Actually for drawing onto controls the use of TextRenderer.DrawText
is recommended over graphics.DrawString
..
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…