[ACCEPTED]-Delphi element alignment - center-delphi-xe6

Accepted answer
Score: 11

Put the elements into their own container, such 5 as a TPanel or TFrame, that is a child of your main 4 container. Set the child container's Align property 3 to alCustom and use the parent container's OnAlignPosition event 2 to keep the child container centered to 1 itself:

// Panel1 is the Parent container for the child panel...
procedure TMyForm.Panel1AlignPosition(Sender: TWinControl; Control: TControl;
  var NewLeft, NewTop, NewWidth, NewHeight: Integer; var AlignRect: TRect;
  AlignInfo: TAlignInfo);
  if Control = ChildPanel then
    NewLeft := AlignRect.Left + ((AlignRect.Width - Control.Width) div 2);
    NewTop := AlignRect.Top + ((AlignRect.Height - Control.Height) div 2);
Score: 3

There is no need for coding anything. Just 8 place panels and other visual objects in 7 the right way an set the properties of the 6 visual objects as shown here:

Align: alNone or alCustom
Anchors: none (akLeft=False, akTop=False, akRight=False, akBottom=False)

Than and an 5 object will stay at its relative horizontal 4 and vertical position. If you place it in 3 the middle in a container it will stay centered.

To 2 center it only vertical set

Align: alNone or alCustom
Anchors: akTop=True OR akBottom=True

To center it 1 only horizontal set

Align: alNone or alCustom
Anchors: akLeft=True OR akRight=True
Score: 2

You can center the control with this little 3 procedure

procedure CenterControl( AControl : TControl );
  if Assigned( AControl.Parent )
      // remove alignment
      AControl.Align := alNone;
      // remove the anchors
      AControl.Anchors := [];
      // center on parent
      AControl.Left := ( AControl.Parent.ClientWidth - AControl.Width ) div 2;
      AControl.Top := ( AControl.Parent.ClientHeight - AControl.Height ) div 2;
    raise Exception.Create( 'Control needs a Parent!' );

If the parent gets resized the 2 control will always be centered, as long 1 as you did not change its size.

Score: 0

In RAD 10+ there is control TRelativePanel 9 which has AlignVerticalCenterWithPanel and 8 AlignHorisontalCenterWithPanel life-save 7 options (and other useful capabilities).

You 6 can also position invisilble line or dot 5 in the center and build other controls around 4 it with TRelativePanel provided properties 3 Above/Below/etc. Worth to mention, control 2 is made on top level Embarcadero quality 1 standards (crashes only in design mode).

More Related questions