Delphi: AutoSize Button, CheckBox or RadioButton

TButton, TCheckBox and TRadioButton don’t have AutoSize property. We have to update its Width after changing its Caption text.

function TForm1.ScaleDimension(const X: Integer): Integer;
begin
  Result := MulDiv(X, Screen.PixelsPerInch, PixelsPerInch);
end;

procedure TForm1.ResizeMyButton(MyButton: TButton);
var
  MyBitmap: TBitmap;
begin
  MyBitmap := TBitmap.Create;
  try
    MyBitmap.Canvas.Font.Assign(MyButton.Font);
    MyButton.Width:=MyBitmap.Canvas.TextWidth(MyButton.Caption)+ScaleDimension(30);
  finally
    MyBitmap.Free;
  end;
// 30 is buffer that includes button width itself and some space
// ScaleDimension provides High-DPI support
end;

procedure TForm1.ResizeMyCheckBox(MyCheckBox: TCheckBox);
var
  MyBitmap: TBitmap;
begin
  MyBitmap := TBitmap.Create;
  try
    MyBitmap.Canvas.Font.Assign(MyCheckbox.Font);
    MyCheckBox.Width:=MyBitmap.Canvas.TextWidth(MyCheckBox.Caption)+ScaleDimension(30);
  finally
    MyBitmap.Free;
  end;
// 30 is buffer that includes checkbox width itself and some space
// ScaleDimension provides High-DPI support
end;

procedure TForm1.ResizeMyRadioButton(MyRadioButton: TRadioButton);
var
  MyBitmap: TBitmap;
begin
  MyBitmap := TBitmap.Create;
  try
    MyBitmap.Canvas.Font.Assign(MyRadioButton.Font);
    MyRadioButton.Width:=MyBitmap.Canvas.TextWidth(MyRadioButton.Caption)+ScaleDimension(30);
  finally
    MyBitmap.Free;
  end;
// 30 is buffer that includes radiobutton width itself and some space
// ScaleDimension provides High-DPI support
end;

begin
  Button1.Caption:='Button Text';
  ResizeMyButton(Button1);

  CheckBox1.Caption:='CheckBox Text';
  ResizeMyCheckbox(CheckBox1);

  RadioButton1.Caption:='RadioButton Text';
  ResizeMyRadioButton(RadioButton1);
end;

One thought on “Delphi: AutoSize Button, CheckBox or RadioButton

  1. Vista+

    function RadioButtonGetIdealSize(R: TRadioButton): TSize;
    const
    BCM_GETIDEALSIZE = $1601;
    begin
    Result.cx := 0;
    Result.cy := 0;
    if R = nil then Exit;
    if SendMessage(R.Handle, BCM_GETIDEALSIZE, 0, Integer(@Result)) = 0 then
    begin
    Result.cx := R.Width;
    Result.cy := R.Height;
    end;
    end;

    Like

Leave a comment