Home > Back-end >  in c# winform, How to keep a control always in the center bottom of a form when form's size cha
in c# winform, How to keep a control always in the center bottom of a form when form's size cha

Time:11-14

in c# winform, How to keep a control always in the center bottom of a form when form's size changed?

if I use DockStyle.Bottom, I can't set its width.

I tried it out. The following is the code, but I don't know why? It's mainly because I don't understand why the Left value will change when the Anchor. Bottom is set?

    public void Run()
    {
        Form form = new Form();
        form.Width = 600;
        form.Height = 600;

        Button btnOK = new Button();
        btnOK.Text = "OK";
        btnOK.Left = form.ClientSize.Width / 2 - btnOK.Width;
        btnOK.Top = 0;
        btnOK.Anchor = AnchorStyles.Bottom;
        Button btnCancel = new Button();
        btnCancel.Text = "Cancel";
        btnCancel.Left = form.ClientSize.Width / 2;
        btnCancel.Top = 0;
        btnCancel.Anchor = AnchorStyles.Bottom;

        Panel panel = new Panel();
        panel.Height = btnOK.Height;
        panel.Width = form.ClientSize.Width;
        panel.Dock = DockStyle.Bottom;
        panel.Controls.Add(btnOK);
        panel.Controls.Add(btnCancel);

        form.Controls.Add(panel);
        form.Show();
    }
    

enter image description here

CodePudding user response:

Use a TableLayoutPanel. You can Dock it to the Bottom or Anchor it to the Bottom, Left and Right. You would have one row then have a column with an absolute width for each control and one extra column on the left and another on the right with 50% width. Those two extra columns will take up half the empty space each, thus keeping the others in the middle.

  • Related