Search code examples
delphivcl

How to close a modal form from which I call a modal form


The main form opens a modal form B.
Form B opens a modal form C.

How can I close form B before form C opens?


Solution

  • The trick is to postpone the call to ShowModal of FormC until FormB is closed. The following code can be placed inside a ButtonClick event handler. It makes use of the ForceQueue method available in recent Delphi versions. The Anonymous Method given to ForceQueue will be executed in the main thread at some later point. This allows the modal FormB to finish before FormC is shown.

      TThread.ForceQueue(nil,
        procedure
        var
          frm: TFormC;
        begin
          frm := TFormC.Create(Application);
          try
            frm.ShowModal;
          finally
            frm.Free;
          end;
        end
      );
      ModalResult := mrOK;