Delphi/C++ Builder の MessageDlg をフォームの中央に表示

MessageDlg っぽくて、指定(メイン)フォームの中央に表示

位置を指定できる MessageDlgPos が存在するものの、表示しようとしているダイアログのサイズが分からなければ、位置を決められないわけで...
function MsgDlg(AMessage: string; DlgType: TMsgDlgType = mtInformation; Buttons: TMsgDlgButtons = [mbOK]; AForm: TForm = nil): TModalResult;
var ARect: TRect;
    MsgForm: TForm;
begin
    if (AForm = nil) then begin
        if (Application.MainForm <> nil) then begin
            GetWindowRect(Application.MainForm.Handle, ARect);
        end
        else begin
            Result := MessageDlg(AMessage, DlgType, Buttons, 0);
            Exit;
        end;
    end
    else begin
        GetWindowRect(AForm.Handle, ARect);
    end;

    MsgForm := CreateMessageDialog(AMessage, DlgType, Buttons);
    try
        MsgForm.Top := ARect.Top + (ARect.Bottom - ARect.Top - MsgForm.Height) div 2;
        MsgForm.Left := ARect.Left + (ARect.Right - ARect.Left - MsgForm.Width) div 2;
        // MoveMouseCursorToDefaultButton(MsgForm);
        Result := MsgForm.ShowModal;
    finally
        MsgForm.Free;
    end;
end;
既定のボタンへカーソルを移動するには、MoveMouseCursorToDefaultButton 関数を併用します



デフォルトが設定されているので、メインフォーム中央の場合、フォームを指定する必要はありません
MsgDlg('処理が完了しました'); // Information アイコンで OK ボタンのみ
みたいに利用します

コメント