How to make group box text alignment center in win forms?

后端 未结 4 1358
清歌不尽
清歌不尽 2021-01-02 15:22

I am using a group box and there are several controls inside this.

My requirement is to set the group box title to the middle of the group box instead of Left.

4条回答
  •  春和景丽
    2021-01-02 15:36

    you can extend the group box class like this.

     public class CustomGrpBox : GroupBox
        {
            private string _Text = "";
            public CustomGrpBox()
            {
                //set the base text to empty 
                //base class will draw empty string
                //in such way we see only text what we draw
                base.Text = "";
            }
            //create a new property a
            [Browsable(true)]
            [Category("Appearance")]
            [DefaultValue("GroupBoxText")]
            [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
            public new string Text
            {
                get
                {
    
                    return _Text;
                }
                set
                {
    
                    _Text = value;
                    this.Invalidate();
                }
            }
            protected override void OnPaint(PaintEventArgs e)
            {
    
                  //first let the base class to draw the control 
                  base.OnPaint(e);
                  //create a brush with fore color
                  SolidBrush colorBrush = new SolidBrush(this.ForeColor);
                  //create a brush with back color
                  var backColor = new SolidBrush(this.BackColor);
                  //measure the text size
                  var size = TextRenderer.MeasureText(this.Text, this.Font);
                  // evaluate the postiong of text from left;
                  int left = (this.Width - size.Width) / 2;
                  //draw a fill rectangle in order to remove the border
                  e.Graphics.FillRectangle(backColor, new Rectangle(left, 0, size.Width, size.Height));
                  //draw the text Now
                  e.Graphics.DrawString(this.Text, this.Font, colorBrush, new PointF(left, 0));
    
            }
        }
    

    add the above class into your project and use "CustomGrpBox" instead of "GroupBox" which will be created after build in your tool box.

    and you can set the text any time like this.

    private void Form2_Load(object sender, EventArgs e)
        {
            customGrpBox1.Text = "Hello World";
        }
    

    it will look like this in design time visual studio

提交回复
热议问题