I'm clueless and hope someone could help me with this one:
I Have a form which has a public method which receives a string and an array of string. The method creates as many buttons as elements array have. Everything works fine.
Then I wanted have all buttons with the same width: the width of the button with the longest caption.
So I did this:
{_________________________________________________________________ ButtonClick }
procedure TFormMensaje.ButtonClick(Sender: TObject);
var
Msj: string;
begin
if Sender is TButton then begin
FResponse := (Sender as TButton).Caption; // property FResponse: string;
end;
end; {<--- ButtonClick }
function TFormMessage.ShowMsg(const Mssg: string; const BtnLst: array of string): string;
var
i, TheLonger: Integer;
B: TButton;
begin
Result := '';
TheLonger := 0;
SetLength(FBtnLst, High(BtnLst+1)); // property: FBtnLst Array of TButton
for i := 0 to High(BtnLst) do begin
B := TButton.Create(Self);
FBtnLst[i] := B;
{ Here I set properties like parent, position, etc. }
B.OnClick := @ButtonClick;
B.Autosize := True;
B.Caption := BtnLst[i];
TheLonger := Max(TheLonger, B.With);
end;
for i := 0 to High(FBtnLst) do begin
FBtnLst[i].AutoSize := FALSE;
FBtnLst[i].Width := TheLongest;
end;
ShowModal;
Result := FResponse;
end;
The problem with that code is that it always set the width to 75 and not the "real" button's width.
I did a workaround by doing this
//.....
TheLongest := Max(TheLongest, Canvas.TextExtent(B.Caption).cx);
//...
//...
FBtnLst[i].Width := TheLongest + AN_ARBITRARY_MARGIN_CONSTANT;
//...
It works but I don't like it because different OS / Themes might have or need different margins.
So here comes my question: Does anybody knows a better way to do it?