1. Technology
Centering the MessageDlg dialog inside a form
How to make your MessageDlg's center on your form instead of the screen.
 Win prizes by sharing code!
Do you have some Delphi code you want to share? Are you interested in winning a prize for your work?
Delphi Programming Quickies Contest
 Join the Discussion
"Post your views, comments, questions and doubts to this article."
Discuss!
 Related Resources
• Working with Windows dialogs: various tips and articles

Article submitted by Carl Dippel for the Delphi Programming Quickies Contest.

MessageDlg
GExperts makes using MessageDlg very easy. If you haven't installed GExperts for use in Delphi you really should; it has a myriad of useful tools. The one I use the most is the one that allows me to create a MessageDlg code with just a few mouse clicks.

Here is a screen shot of the GExperts dialog box:

Type Hello in the Message window and click OK and this code is placed into your code.

MessageDlg('Hello', mtInformation, [mbOK], 0);

  

When this code is executed this message is displayed in the middle of the screen.

Therein lies the problem. I prefer to have the message centered over my form instead of centered in the screen. I could have edited the code but I have many messages and I like to use the GExperts code generator. I need a way to make all the messages appear in center of my form without changing the code for each message.

Center over Form not Screen
The solution is easy just create a procedure local to your form with the same name, MessageDlg. First create the formal declaration in your form's private section:

  private
   { Private declarations }
   function MessageDlg(const Msg: string; DlgType: TMsgDlgType;
      Buttons: TMsgDlgButtons; HelpCtx: Integer): Integer;
  public
   { Public declarations }

Press Ctrl-Shift-C to complete the declaration and this will be created in the implementation section

function TForm1.MessageDlg(const Msg: string; DlgType: TMsgDlgType;
  Buttons: TMsgDlgButtons; HelpCtx: Integer): Integer;
begin

end;

Between the begin-end pair enter this code.

function TForm1.MessageDlg(const Msg: string; DlgType: TMsgDlgType;
  Buttons: TMsgDlgButtons; HelpCtx: Integer): Integer;
begin
  with CreateMessageDialog(Msg, DlgType, Buttons) do
    try
      Position := poOwnerFormCenter;
      Result := ShowModal
    finally
      Free
    end
end;

Now all the messages will appear centered over you form not in the center of the screen.

©2014 About.com. All rights reserved.