views:

3658

answers:

6

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.

+14  A: 

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 the control centred in that direction when resizing.

splattne
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.
maxwellb
+5  A: 
myControl.Left = (this.ClientSize.Width - myControl.Width) / 2 ;
myControl.Top = (this.ClientSize.Height - myControl.Height) / 2;
Mitch Wheat
A: 

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).

David in Dakota
Could you please elborate? I can't make sense of your answer.
Mitch Wheat
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.
David in Dakota
+1  A: 

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

Robert MacLean
Why is mitch's solution for resizing better than anchoring in the designer?
Ed Sykes
+1  A: 

Both Mitch's and splattne's answers will work. Splattne's answer is, in my opinion, better as you can set it and forget it. Mitch's requires the code to be placed in the form's Resize event as well as in the form's Load event (a la VB6 days!).

I certainly don't miss those epic amounts of VB6 resize code!
pezi_pink_squirrel
AMEN! But, without that struggle we wouldn't appreciate what we have today.
A: 

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.

Chad