2016-07-30 53 views
1

我需要自定义我的组合框,就像这张图片一样。自定义Combobox中的中心文本

enter image description here
我的代码工作fine.But它有2个问题:
1.文本向左移动,当我最小化窗口,如下

enter image description here
2.背景转当另一个窗口覆盖我的应用程序时变绿。

enter image description here

这里是我的代码:

//DrawItem 
protected override void OnDrawItem(DrawItemEventArgs e) 
{ 
    e.DrawBackground(); 
    e.DrawFocusRectangle(); 
    if (e.Index >= 0) { 
    Graphics g = e.Graphics; 
    Brush brs = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? 
    new SolidBrush(SelectedBackColor) : new SolidBrush(e.BackColor); 
    g.FillRectangle(brs, e.Bounds); 
    using (StringFormat sformat = new StringFormat()) { 
    sformat.LineAlignment = StringAlignment.Center; 
     sformat.Alignment = StringAlignment.Center; 
     e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, sformat); 
} 
//paint 
protected override void OnPaint(PaintEventArgs e) 
{ 
    base.OnPaint(e); 
    if (index >= 0) { 
     using (Brush br = new SolidBrush(this.ForeColor)) { 
     StringFormat sformat = new StringFormat(); 
     sformat.LineAlignment = StringAlignment.Center; 
     sformat.Alignment = StringAlignment.Center; 
     e.Graphics.DrawString(this.Text, this.Font, br, this.ClientRectangle, sformat); 
     e.Graphics.DrawImage(Resource1.arrow,this.ClientRectangle.Right - 34, 0,32,32); 
     } 
    } 
} 

这样有什么不好?

+0

你的代码不能编译;至少缺少两个关闭卷曲。请只发布真实的代码! - e.Bounds和/或ClientRectangle实际上是否留下箭头的空间?除此之外:错误情况听起来很有趣。在最小化之后,我想恢复,对齐/位置是否保持错误? – TaW

+0

对不起,我的错误。我认为问题是e.Bounds。 Combobox大小为135,34,e.Bouds为133.当窗口最小化时,e.Bounds为112. e.Bounds在最小化时调整大小。如何解决它?@TaW – Jandy

回答

0

您可以使用Graphics.MeasureString获得字符串的大小来绘制,然后再决定在哪里开始绘制字符串:

SizeF size = new SizeF(); 
size = e.Graphics.MeasureString(this.Text, this.Font); 
PointF DrawPoint = new PointF((this.Width - size.Width)/2, (this.Height - size.Height)/2); 
e.Graphics.DrawString(this.Text, this.Font, br, DrawPoint, sformat); 
+0

对我的迟到感到抱歉。没有什么变化。我正在寻找方法来修复e.Bounds和选择的项目样式,当窗口最小化@ Ashkan Mobayen Khiabani – Jandy

0

我发现了问题是下拉state.I必须检查DroppedDown之前设置画笔。

protected override void OnDrawItem(DrawItemEventArgs e) 
{ 
    e.DrawBackground(); 
    if (e.Index >= 0 && DroppedDown) { 
    Brush brs = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? 
    new SolidBrush(SelectedBackColor) : new SolidBrush(Color.Red); 
    e.Graphics.FillRectangle(brs, e.Bounds); 
    using (StringFormat sformat = new StringFormat()) { 
     sformat.LineAlignment = StringAlignment.Center; 
     sformat.Alignment = StringAlignment.Center; 
     e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, sformat); 
}