Sinisterly
Tutorial C# center your controls - Printable Version

+- Sinisterly (https://sinister.li)
+-- Forum: Coding (https://sinister.li/Forum-Coding)
+--- Forum: Visual Basic & .NET Framework (https://sinister.li/Forum-Visual-Basic-NET-Framework)
+--- Thread: Tutorial C# center your controls (/Thread-Tutorial-C-center-your-controls)



C# center your controls - chunky - 12-29-2017

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:
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:
[Image: 2017-12-29_21_59_47-_Sinister.ly.png]


RE: C# center your controls - Confidential - 04-29-2018

This saved me from committing suicide, thanks.