Share via


Center Align Control In Windows Forms

Question

Monday, October 12, 2009 1:00 PM

Is there a property in windows forms to make sure that a control always stays in the centre even if the form is resized. I basically have a login form and i want my login panel to always be in the center and middle of the form

All replies (5)

Monday, October 12, 2009 1:40 PM âś…Answered | 1 vote

Here is a sample code.

Hope it helps

    public partial class Form1 : Form
    {
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            CenterControlInParent(panel1);
        }
        private void CenterControlInParent(Control ctrlToCenter)
        {
            ctrlToCenter.Left = (ctrlToCenter.Parent.Width - ctrlToCenter.Width) / 2;
            ctrlToCenter.Top = (ctrlToCenter.Parent.Height - ctrlToCenter.Height) / 2;
        }
}

Monday, October 12, 2009 1:38 PM | 1 vote

I don't know any property for this situation. But you can bring the login form components into a one group box. Then write a code into forms sizechanged event:

 

int centerform;
int centerGroup;
       
            centerForm = this.Width / 2;
            centerGroup = groupBox.Width / 2;
            groupStartPosition = centerForm - centerGroup;
            groupBox.Left = groupStartPosition; 

Tuesday, October 13, 2009 9:42 AM

Thanks guys,this was really big help. I though there would be a property for this though. But anyway, problem solved. Thanks again


Friday, February 26, 2010 1:28 PM | 2 votes

Its on my blog but in short: Centre it at design time or on load with code, then remove the anchors in the direction to want to centre it. Removing the anchors forces the control to keep is proportional positioning on the form.
HTH Ciaran http://wannabedeveloper.spaces.live.com


Tuesday, April 3, 2012 3:25 AM

Thanks. Here's the link to your mentioned blog http://wannabedeveloper.wordpress.com/2007/03/23/center-align-on-windows-forms/.

Let me summarize it : by default, the anchor for control are Top|Left. Discarding the Left value, by setting anchor to Top as only value, will make the control located in its proportional location from its container.