55 Votes

Delphi/Lazarus: ShowModal Result

Tip by Progger99 | 2013-05-19 at 22:06

ShowModal shows a window and waits until it is closed. Until closing, you cannot interact with any other window of the application. What many do not know: You can define a result value on closing of the ShowModal Form, which you can use very easily in your program. For example to check which button the user has clicked.


Let's have a look at an example demonstrating this. Our first form is Form1 and we want to display a second window (Form2) with ShowModal. On Form2, we have two buttons to which we have assigned the following code:

procedure TForm2.Button1Click(Sender: TObject);
   ModalResult := 1;

procedure TForm2.Button2Click(Sender: TObject);
   ModalResult := 2;

In Form1, we are showing this form with ShowModal:

procedure TForm1.Button1Click(Sender: TObject);
  k: integer;
  // Example 1
  k := Form2.ShowModal;
  if k = 1 then ShowMessage('Button 1 was clicked!');
  if k = 2 then ShowMessage('Button 2 was clicked!');

  // Example 2
  if Form2.ShowModal = 1 then begin
    ShowMessage('Button 1 was clicked!');
The value we have assigned to ModalResult is the result of ShowModal. At the same time we are setting ModalResult to another value than zero, the form is closed automatically.

In the example, we are setting ModalResult to 1 with Button1 and to 2 with Button2. So, we can check which button was clicked and we can show corresponding messages in the example.

ModalResult Buttons

Next to this method, it is also possible to directly apply one of the standard ModalResults to buttons. For this, buttons are having the property "ModalResult" which we can set to mrOK or mrCancel, for example.

If we have prepared a button in this way, we can retrieve the result in the following way.

if Form2.ShowModal = mrOk then begin
   ShowMessage('The Button with mrOk was clicked!');

So, if the user has clicked on the button with the property ModalResult = True, the form closes automatically without that we have to change anything else on the button properties or events. And we can recognize on the result value of ShowModal which button was clicked by the user.


About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.