How To Move ANY Visible Component at Runtime

This code will move any control at runtime, even non TWinControl descendants.

Make sure ExtCtrls is in your USES clause.
Then set the OnMouseDown event of your controls to the following code.

procedure TForm1.MoveControl(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  TempPanel : TPanel;
  Control : TControl;
begin
  //Release the MOUSEDOWN status
  ReleaseCapture;
  if Sender is TWinControl then
    //Component has a Handle, move it directly
    TWincontrol(Sender).Perform(WM_SYSCOMMAND,$f019,0)
  else
    //Component has no handle, move it in a TPanel
    try
      Control := TControl(Sender);
      TempPanel := TPanel.Create(Self);
      with TempPanel do
      begin
     //Replace component with TempPanel
        Caption := '';
        BevelOuter := bvNone;
        SetBounds(Control.Left,Control.Top,


        Control.Width,Control.Height);
        Parent := Control.Parent;

        //Put our control in the TempPanel
        Control.Parent := TempPanel;

        //Move TempPanel with the control inside it
        Perform(WM_SYSCOMMAND,$F019,0);

        //Put the component where the panel was dropped
      Control.Parent := Parent;
        Control.Left := Left;
        Control.Top := Top;
      end;
    finally
      TempPanel.Free;
    end;
end;

 

Share this article!

Follow us!

Find more helpful articles: