I can't find tools or properties to place a label or a button exactly in the middle of the Form. For example, on the X axis. VS 2015.
-
2Using IDE or using code? – Steve May 02 '18 at 09:24
-
1Possible duplicate of [Centering controls within a form in .NET (Winforms)?](https://stackoverflow.com/questions/491399/centering-controls-within-a-form-in-net-winforms) – MatSnow May 02 '18 at 09:25
-
@**Casiosmu**, you guided me in the right direction. In VS2015 --> Format --> Center in Form -> Vertically/Horizontally. P.S. What's a crooked forum engine! It's hard to get who, when and where answered to you.((( – Msorich May 02 '18 at 09:46
2 Answers
Design time :
In my VisualStudio2010 I have these 2 buttons to center horizontally and vertically:
Its located in the toolbar "Layout". If it isn't, you can add them by clicking the small button to the right. It is also in the Format menu.
To keep centered at Runtime: Turn off all anchoring.
Note:This will keep the control at its relative position as long as it doesn't change it Size. If it does, like autosize Labels
are prone to, you will have to code the Resize
event. Examples are here
-
I have too, but they become active when you're going to align at least two components at the Form field. Not Form itself and component. That's the point! – Msorich May 02 '18 at 09:24
-
maybe they have changed this, but in my VS2010 this works for also for a single selection. You should add to your question that you already tried this! – casiosmu May 02 '18 at 09:28
-
1
-
2
-
2Ah, I had to add them because they are not shown by default. Please edit your post to include this info (and also so I can go from -1 to +1!) – TaW May 02 '18 at 09:34
-
2In Visual Studio 2019 I had to enable the Layout toolbar and then click "Add or Remove Buttons" on the toolbar and enable "Center Horizontally" and "Center Vertically" to see the buttons mentioned in this post. It's interesting that those 2 options are not displayed by default. – Alex Myers Apr 03 '19 at 20:34
For controls that may change in size, you need to catch the Resize event.
In my case I have a Panel, representing a page, inside another Panel which is the workspace. The workspace is set to autoscroll. In this scenario, it's important that the control is only centered when smaller than the container.
Whenever the form changes size or when I change the content, I call this function:
private void resetPagePos()
{
int wWS = pnlWorkspace.Width;
int hWS = pnlWorkspace.Height;
int wPage = pnlPage.Width;
int hPage = pnlPage.Height;
pnlPage.Location = new Point(Math.Max(0, (wWS - wPage) / 2), pnlPage.Top = Math.Max(0, (hWS - hPage) / 2));
}
The use of Math.Max(0, ...) makes sure that if the item doesn't fit, and the scrollbars are activates, then our page scrolls correctly. If the Left or Top are set to a negative number, you would get unwanted side-effects.

- 5,260
- 4
- 36
- 43