Centering controls within a form in .NET (Winforms)?
Asked Answered
A

11

160

I'm trying to center a fixed size control within a form.

Out of interest, is there a non-idiotic way of doing this? What I really want is something analogous to the text-align css property.

At the moment, I'm setting the padding property of the surrounding form to a suitable size and setting the Dock property of the control to fill.

Antin answered 29/1, 2009 at 12:27 Comment(1)
Simple solution here.Desdee
P
288

You could achieve this with the use of anchors. Or more precisely the non use of them.

Controls are anchored by default to the top left of the form which means when the form size will be changed, their distance from the top left side of the form will remain constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized.

Turning off the anchor in a direction will keep a control centered when resizing, if it is already centered. In general, a control not anchored maintains its proportional position to the dialog. E.g. If you put a control at X=75% of the dialog width and turn off left/right anchors, the control will maintain its center at X=75% of the dialog width.

NOTE: Turning off anchoring via the properties window in VS2015 may require entering None (instead of default Top,Left)

Pastoral answered 29/1, 2009 at 12:34 Comment(12)
So, you could place the control in the center of the form (approx or exact using Properties panel), or in Form.Load event handler, setting the Control.Left, Control.Top properties with respect to Control.Size and Form.Size.Arrogance
Great, I never thought about quit all sides on Anchor property, now if I resize the control keeps centered. !great!Melise
Then if I place a label in a form at centre and set its Anchor to None, why doesn't it keep itself at centre when the form window is maximized?Gardenia
@Gardenia is the label inside another container which is anchored?Pastoral
@Gardenia I tested it. It works on my form. Are you sure that you set the "Anchor" property of the label? Try it on a new form and see what's the difference.Pastoral
Wait, I was wrong about it being in a Form. It is inside a UserControl whose Anchor is set to Top | Left but it's Dock is set to Fill too. So, shouldn't it center it still?Gardenia
@Gardenia It centers, but in relation to the UserControl. The label is always in the center of the UserControl. In your case, you should "unanchor" the UserControl.Pastoral
Sorry for being sticky on this. I need to understand a bit more. How the label is always in the center of the UserControl? If I place a border at the UserControl, it shows the border correctly according to maximized window but the label is no more at center.Gardenia
@Gardenia I think this is not the right place to communicate. ;-) Read this: devx.com/dotnet/Article/6964/1954 it's not difficult to grasp the concept.Pastoral
Awesome. I've worked with UIs in .net for years, I've used all kinds of variations of anchors, and I totally didn't know the (quite useful) behavior of setting it to None until just now. Craziness.Bahaism
You also need to set Dock to Fill. Also I needed to have the Label inside a Panel.Elbow
@Elbow depends on your use case. Normally you don't need to do that.Pastoral
S
134
myControl.Left = (this.ClientSize.Width - myControl.Width) / 2 ;
myControl.Top = (this.ClientSize.Height - myControl.Height) / 2;
Selfpossession answered 29/1, 2009 at 12:36 Comment(5)
I think this is the correct answer to actually keep the control at centre even when the form is resized at runtime.Gardenia
Add the above code to a System.Windows.Forms.Form SizeChanged event and voila.Gonfanon
This, together with the SizeChanged event of the control you want to keep centered, is the solution to keep your control centered if your control can change its size independently of its parent form.Jobbery
Great answer, however doesnt apply to the textbox control with multiline false, i found simply myControl.Location = new Point(this.Width / 2 - myControl.Width / 2, this.Height / 2 - myControl.Height / 2) Works correctlyShelter
If you want to center a control on another such as loading panel on a grid, use below: private void Form1_SizeChanged(object sender, EventArgs e) { PicLoading.Left = dataGridView1.Width / 2; PicLoading.Top = dataGridView1.Height / 2; }Navaho
I
53

Since you don't state if the form can resize or not there is an easy way if you don't care about resizing (if you do care, go with Mitch Wheats solution):

Select the control -> Format (menu option) -> Center in Window -> Horizontally or Vertically

Infamy answered 29/1, 2009 at 13:12 Comment(4)
Why is mitch's solution for resizing better than anchoring in the designer?Ashmore
Yes..it works. By using your guide:- Select control. Go to Format --> Center in Form --> Select Vertically and Horizontally. Then go to anchor, unselect Top and Left (default control anchor)..and it did center on the screen..greatlyPecksniffian
@EdSykes If the control you want to keep centered can resize independently of the form. The anchoring solution will not recenter it and allow the control to grow off center.Jobbery
This is the best answer. I spent many hours to align the controls manually.Incult
T
10

I found a great way to do this and it will work with multiple controls. Add a TableLayout with 3 columns. Make the center column an absolute size (however much room you need). Set the two outside columns to 100%. Add a Panel to the center column and add any controls you need and place them where you want. That center panel will now remain centered in your form.

Than answered 13/7, 2010 at 18:6 Comment(2)
All right, but sometime set center column to auto size is more suitable.Gardie
A single cell TableLayoutPanel that contains an undocked panel also works fine.Bristletail
S
6

To center Button in panel o in other container follow this step:

  1. At design time set the position
  2. Go to properties Anchor of the button and set this value as the follow image

enter image description here

Stringency answered 23/9, 2017 at 7:52 Comment(0)
N
6

In addition, if you want to align it to the center of another control:

//The "ctrlParent" is the one on which you want to align "ctrlToCenter".
//"ctrlParent" can be your "form name" or any other control such as "grid name" and etc.
ctrlToCenter.Parent = ctrlParent;

ctrlToCenter.Left = (ctrlToCenter.Parent.Width - ctrlToCenter.Width) / 2;
ctrlToCenter.Top = (ctrlToCenter.Parent.Height - ctrlToCenter.Height) / 2;
Navaho answered 5/2, 2018 at 19:50 Comment(0)
T
2

You can put the control you want to center inside a Panel and set the left and right padding values to something larger than the default. As long as they are equal and your control is anchored to the sides of the Panel, then it will appear centered in that Panel. Then you can anchor the container Panel to its parent as needed.

Torre answered 18/4, 2012 at 16:5 Comment(1)
For multiple controls: put the controls on a panel then remove the panel anchors.Cinerarium
T
0

It involves eyeballing it (well I suppose you could get out a calculator and calculate) but just insert said control on the form and then remove any anchoring (anchor = None).

Teofilateosinte answered 29/1, 2009 at 12:37 Comment(4)
Could you please elborate? I can't make sense of your answer.Selfpossession
In my attempt to answer quickly (I always get beaten to the punch on StackOverflow) I was saying what the user splattne said more eloquently: turn off anchoring for the control you want to center.Teofilateosinte
FYI, Visual Studio's forms Layout toolbar has "Center Horizontally" and "Center Vertically" buttons which eliminate the need to "eyeball" anything. Not sure if it existed pre-VS2010, but it is quite useful.Nanete
Note that the Center Horizontally and Center Vertically Dan Bechard mentioned are not visible in the toolbar by default, you need to enable them.Consolute
S
0

you can put all your controls to panel and then write a code to move your panel to center of your form.

panelMain.Location = 
    new Point(ClientSize.Width / 2 - panelMain.Size.Width / 2, 
              ClientSize.Height / 2 - panelMain.Size.Height / 2);

panelMain.Anchor = AnchorStyles.None;
Spermine answered 27/12, 2017 at 20:49 Comment(0)
N
0

To keep the control centered even the form or parent control were resize.

  1. Set the following properties of the parent element (you can set it through the property window):
    parentControl.AutoSize = true;
    parentControl.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; 
  1. Put this code in the Resize event of the form or the parent control (if the control is inside of another control).
    controlToCenter.Left = (parentControl.Width- controlToCenter.Width) / 2;
    controlToCenter.Top = (parentControl.Height - controlToCenter.Height) / 2;
  1. If the parent control is docked to the form, add this line of code.
       //adjust this based on the layout of your form
       parentControl.Height = this.ClientSize.Height; 
Nocturne answered 8/7, 2021 at 14:31 Comment(0)
R
0

So, I am currently working on a pagination control and I came up with the following to achieve the below result.

example

  • Add a PanelLayout to your container (e.g. form or usercontrol)
  • Set the PanelLayout properties:
    • Dock: Bottom (or Top)
    • AutoSize: False

This will center the PanelLayout horizontally. Now, in your codebehind, do something like this:

    public MyConstructor()
    {
        InitializeComponent();

        for (var i = 0; i<10; i++)
        {
            AddButton(i);
        }
    }

    void AddButton(int i)
    {
        var btn = new Button();
        btn.Width = 30;
        btn.Height = 26;
        btn.Text = i.ToString();
        this.flowLayoutPanel1.Controls.Add(btn);
        btn.Anchor = AnchorStyles.None;
    }

There is a ceveat, however. If I make my form too small (horizontally) buttons will "disappear" outside of the viewport. In my case, that's not a problem, but you could take care of this by writing code that listens to the Resize event, and remove elements (buttons) based on the viewport Width.

Rockery answered 1/10, 2021 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.