1

centering, controls, C#, visual C#

Free lines C# 1 revisions 77 10 months ago 10 months ago
public void centerControl(Control accessControl, Control parentControl, bool centerX, bool centerY)
{ /* Example of usage: centerControl(pictureBox, panelMain, true, true); */
   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);
}

Call this function with proper args to center elements in a parent container

1st arg: name of the control you wish to have centered 2nd arg: name of the parent control you wish to have the item centered in 3rd arg: center horizontally, boolean, true|false 4th arg: center vertically, boolean, true|false