HelmBurger
HelmBurger

Reputation: 1298

how to keep objects in place when window is resized in C#

How can I keep the objects of my window (buttons, labels, etc) in center when the window is resized?

Currently, I have 3 buttons in a Windows Form. When I maximize the window, the buttons stay at the top left section of the window. I want them to be in the center as they were when the window was not maximized.

Any help?

Upvotes: 14

Views: 40580

Answers (4)

Grzegorz W
Grzegorz W

Reputation: 3517

To keep your layout fixed and in the middle do this:

  1. On your Form add TableLayoutPanel.
  2. Set it's Dock property to Fill.
  3. Create 3 rows and 3 columns.
  4. Edit rows and columns - set 50% for first and last column and row.
  5. Set fixed size for middle row and column.
  6. Place Panel or anything else you like in 2nd row and 2nd column. It will always be in the middle.

Upvotes: 4

SirDuckduck
SirDuckduck

Reputation: 536

You should set the Anchor properties of the object to none,

This will keep it in the middle.

Upvotes: 31

Dan Puzey
Dan Puzey

Reputation: 34198

Set the Anchor property of your controls correctly. By default your control is anchored to Top,Left. If you clear this property (anchor to nothing, essentially), your button will remain centered.

(It may seem like you want to anchor to all four sides, but in reality what this will do is resize your button to fill the form!)

Upvotes: 4

LightStriker
LightStriker

Reputation: 21014

If you are using the visual designer of Visual Studio (And you have no reason not to), the property of your control you seek to manage how they are placed inside a form is "Anchor". By default, when you create a new control, it is set to "Top-Left", which mean they would stay in a fixed position to the top left of your form. You can change that to anchor them to anything.

You can also disable the anchors and control their position by overriding the Resize method of the form.

Upvotes: 0

Related Questions