C# center your controls 12-29-2017, 10:05 PM
#1
Introduction:
I just wrote this little function for one of my tools and I thought it might be useful.
Parameters:
accessControl - The control you wanna center
parentControl - Thre control that's around the accessControl
centerX - boolean that defines whether you wanna center your control horizontally
centerY - boolean that defines whether you wanna center your control vertically
Function:
Example usage:
Call the function in the Form_Resize event in order to automatically center it in case the user is changing the form size.
Result:
I just wrote this little function for one of my tools and I thought it might be useful.
Parameters:
accessControl - The control you wanna center
parentControl - Thre control that's around the accessControl
centerX - boolean that defines whether you wanna center your control horizontally
centerY - boolean that defines whether you wanna center your control vertically
Function:
Code:
public void centerControl(Control accessControl, Control parentControl, bool centerX, bool centerY)
{
int newX = accessControl.Location.X, newY = accessControl.Location.Y;
if (centerX)
{
newX = (parentControl.Width - accessControl.Width) / 2;
}
if (centerY)
{
newY = (parentControl.Height - accessControl.Height) / 2;
}
accessControl.Location = new Point(newX, newY);
}Example usage:
Call the function in the Form_Resize event in order to automatically center it in case the user is changing the form size.
Code:
centerControl(pictureBoxSinisterly, panelMain, true, true);Result:




![[+]](https://sinister.li/images/modern/collapse_collapsed.png)