Mirror

Implement forms that are modal only towards their owner form (Views: 100)


Problem/Question/Abstract:

I have a form of which any number of instances can be created and used at once. From each of these forms the user can open another form. This form must however be modal to its creator (the first form), but not to the rest of the application.

Answer:

Create the modal form with the calling form as Owner, not with pplication as owner. In the modal form override the CreateParams method as

{ ... }
inherited;
params.WndParent := (Owner as TForm).handle;

Add a public class function to the modal form:

class function ShowForm(aOwner: TForm): TModalform;

implemented as

class function TModalForm.ShowForm(aOwner: TForm): TModalForm;
begin
  Result := TModalForm.Create(aOwner);
  aOwner.Enabled := False;
  Result.Show;
end;

Use this method to create instances of the form instead of calling the constructor directly. We also need a handler for OnClose that does

Action := caFree;
(Owner as TForm).Enabled := true;

If you do need to communicate back a modal result to the caller you will need to add a public event to the pseudomodal form to which the caller can attach a handler. This event would then be called from the OnClose event handler, passing the modalresult. Note that any buttons that should close the form with a modalresult need to explicitely call the Close method, since the modal message loop is not used that will not happen on its own.

<< Back to main page