Login Register






Tutorial C# center your controls filter_list
Author
Message
C# center your controls #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:
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]

Reply

RE: C# center your controls #2
This saved me from committing suicide, thanks.

Reply