5 5 Votes

Delphi/Lazarus: ShowModal Result

Tip by Progger99 | 19/05/2013 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.

Example

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);
begin
   ModalResult := 1;
end;

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

In Form1, we are showing this form with ShowModal:

procedure TForm1.Button1Click(Sender: TObject);
var
  k: integer;
begin
  // 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!');
  end;
end;
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!');
end;

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.

ReplyPositiveNegative

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

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.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.