Generic dialog with custom captions for buttons

Roland Bengtsson picture Roland Bengtsson · Mar 24, 2011 · Viewed 19.6k times · Source

I know this issue have been up since before (ex. Best way to show customized message dialogs), but I still don't find what I want.

I started like this:

class function TAttracsForm.MessageDlg(const aMsg: string; aDlgType: TMsgDlgType; Buttons: TMsgDlgButtons; aCaptions: array of String; aDefault: TMsgDlgBtn): TModalResult;
var
  vDlg: TForm;
  i: Integer; 
begin
  if aButtons.Count = aCaptions.Count then
  begin
    vDlg := CreateMessageDialog(aMsg, aDlgType, Buttons);
    try
      for i := 0 aCaptions.Count - 1 do
        TButton(vDlg.FindComponent(Buttons[i].Caption)).Caption := aCaptions[i]; 

      vDlg.Position := poDefaultPosOnly;
      Result := vDlg.ShowModal;
    finally
      vDlg.Free;
    end;
  end;
end;

And the call would look like:

if (MessageDlg('Really quit application ?', mtWarning, 
       [mbNo, mbCancel, mbYes], {'No save', 'Cancel', 'Save'}) = mrYes) then

But the above code of course don't compile. I don't know how to get one item of an set in the loop and how to get the total count of it in the beginning.

Answer

Mohammad picture Mohammad · Sep 4, 2013

you can use this code:

function MyMessageDlg(CONST Msg: string; DlgTypt: TmsgDlgType; button: TMsgDlgButtons;
  Caption: ARRAY OF string; dlgcaption: string): Integer;
var
  aMsgdlg: TForm;
  i: Integer;
  Dlgbutton: Tbutton;
  Captionindex: Integer;
begin
  aMsgdlg := createMessageDialog(Msg, DlgTypt, button);
  aMsgdlg.Caption := dlgcaption;
  aMsgdlg.BiDiMode := bdRightToLeft;
  Captionindex := 0;
  for i := 0 to aMsgdlg.componentcount - 1 Do
  begin
    if (aMsgdlg.components[i] is Tbutton) then
    Begin
      Dlgbutton := Tbutton(aMsgdlg.components[i]);
      if Captionindex <= High(Caption) then
        Dlgbutton.Caption := Caption[Captionindex];
      inc(Captionindex);
    end;
  end;
  Result := aMsgdlg.Showmodal;
end;

For example:

MyMessageDlg('Hello World!', mtInformation, [mbYes, mbNo],
      ['Yessss','Noooo'], 'New MessageDlg Box'):