Skip to content
November 26, 2009 / lawrencebarsanti

Center a dialog box with Delphi

If you use Delphi, then you have likely used the functions ShowMessage, ShowMessagePos,  MessageDlgPos, etc…  These functions are nice because the allow you to display a quick message to the user with very little code (typically 1 line).  Unfortunately, the use of these functions usually leads to some variant of the question.

‘How can I center this dialog box in the application window?’

This seems like it should be easy to do but I have wasted a lot of time trying to find an elegant way to do this.  After some searching I discovered that all of the function listed above ultimately call the function CreateMessageDialog 1.  This function returns a form that can be resized and/or repositioned as necessary before showing.  However, using this function also means more code which makes it inconvenient to use.  If you don’t mind the extra code, just use CreateMessageDialog in place of ShowMessage, ShowMessagePos,  MessageDlgPos, etc…

I created a simple wrapper for CreateMessageDialog that is very similar to MessageDlgPos but my version allows you control the location of the dialog box by passing a TPosition value.  This way you can just write something like

ShowMessageDialog(‘Hi.’, mtInformation, poMainFormCenter, [mbOk]);

Here is the code.  Please leave a comment if you know of a better approach.

function ShowMessageDialog(const Msg: string; DlgType: TMsgDlgType; DlgPos: TPosition;
  Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): TModalResult; overload;
  Dialog: TForm;
  Dialog := CreateMessageDialog(Msg, DlgType, Buttons, DefaultButton);
    Dialog.Position := DlgPos;
    Result := Dialog.ModalResult;

function ShowMessageDialog(const Msg: string; DlgType: TMsgDlgType; DlgPos: TPosition;
  Buttons: TMsgDlgButtons): TModalResult; overload;
  DefaultButton: TMsgDlgBtn;
  if mbOk in Buttons then DefaultButton := mbOk else
    if mbYes in Buttons then DefaultButton := mbYes else
      DefaultButton := mbRetry;

  Result := ShowMessageDialog(Msg, DlgType, DlgPos, Buttons, DefaultButton);

1. As of Vista, these functions will try to use a Task Dialog instead of calling CreateMessageDialogs.  If you just need a regular ole dialog box, this code will work fine.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: