Create component at runtime

Posted in Components

Do not forget that all components in Delphi are the objects. Call Create method to create the component and destruct it by Free method. If the component is a window, set parent window and position. This code showing it:

procedure TForm1.Button1Click(Sender: TObject);
var
  Button: TButton;
begin
  Button:=TButton.Create(Form1);
  try
    with Button do 
    begin
      Parent:=Self;
      Left:=Random(Form1.ClientWidth-Width);
      Top:=Random(Form1.ClientHeight-Height);
      Caption:='Button';
    end;
  except
    Button.Free;
  end;
end;