Move control at runtime

Posted in Components

To move control at runtime use mouse events (capture mouse events to prevent default click processing):

type
  TForm1 = class(TForm)
  ...
  private
    { Private declarations }
    Dragged: Boolean;
    OldPos: TPoint;
  ...

procedure TForm1.Button1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if RadioGroup1.ItemIndex=0 then
  begin
    Dragged:=True;
    GetCursorPos(OldPos);
    SetCapture(Button1.Handle);
  end;
end;

procedure TForm1.Button1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
var
  NewPos: TPoint;
begin
  if Dragged then
    with Button1 do
    begin
      GetCursorPos(NewPos);
      Left:=Left-OldPos.X+NewPos.X;
      Top:=Top-OldPos.Y+NewPos.Y;
      OldPos:=NewPos;
    end;
end;

procedure TForm1.Button1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Dragged then
  begin
    ReleaseCapture;
    Dragged:=False;
  end;
end;