I created the custom combobox on .net framework 1.1, i can custom draw dropdown items, but i can't set or draw the combobox text on Middle Left , combobox text always render top left , but i need text should be render on middle left.
[ToolboxBitmap(typeof(ComboBox))]
public class MenComboBox :ComboBox
{
private Image _image = Image.FromFile("Expand.png");
public MenComboBox()
{
this.DrawMode = DrawMode.OwnerDrawFixed;
this.BackColor = Color.White;
this.ItemHeight = 18;
this.Font = new Font("Arial",12f,FontStyle.Regular);
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (!DesignMode)
{
if (e.Index > -1)
{
int textHeight = (int)e.Graphics.MeasureString(this.Items[e.Index].ToString(), e.Font).Height;
Point textPos = new Point(e.Bounds.X + 4, e.Bounds.Y + ((this.ItemHeight - textHeight) / 2));
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
e.Graphics.FillRectangle(Brushes.Blue, e.Bounds);
e.Graphics.DrawString(this.Items[e.Index].ToString(),e.Font,Brushes.White,textPos);
}
else
{
e.Graphics.FillRectangle(Brushes.White, e.Bounds);
e.Graphics.DrawString(this.Items[e.Index].ToString(),e.Font,Brushes.Black,textPos);
}
}
}
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x000F)
{
using (Graphics g = this.CreateGraphics())
{
g.FillRectangle(new SolidBrush(BackColor), this.ClientRectangle);
g.DrawRectangle(Pens.Blue, new Rectangle(this.ClientRectangle.X, this.ClientRectangle.Y, this.ClientRectangle.Width - 1, this.ClientRectangle.Height - 1));
Rectangle rect = new Rectangle(this.Width - 15, 3, 12, this.Height - 6);
g.FillRectangle(new SolidBrush(BackColor), rect);
g.DrawImage(this._image, this.Width - 16, (this.Height - 8) / 2);
g.Dispose();
}
}
}
}
In an owner draw
ComboBox
the text of theEdit
part of the control will always be shown at top left, regardless of the height of theItemHeight
.To position the
Edit
part vertically in middle, you can find theEdit
element usingGetComboBoxInfo
and then usingSetWindowPos
set a new position for it to stand vertically in middle of theComboBox
.You need to reposition it when the control size changes. Also you need to fill the background of
ComboBox
with a Color.Here is the code that I used:
ok, below code doesn't answer the actual question about the Text portion; Hans got it right, as usual.
I keep the answer because I think it does a few things better than OP code..
Instead of calculating a centered position I use the
DrawString
overload that takes a target rectangle and add aStringFormat
to center in both directions.StringFormat
was available since .Net 1.1 and indeed isIDisposable
, so we should dipose of each we create, best in ausing
clause..Note that for drawing controls the use of
TextRenderer
is encouraged but only came with .Net 2.0.Also note that I substituted the
Brushes
forSystemBrushes
..Also: My ComboBox doesn't place the text in its Text portion top-left but middle-left. Maybe the old .Net1.1 control is the culprit?