Closing modal form(s) from outside and opening a new modal form
<p>In my main form I have a button that opens a modal <code>Form2</code> (which may open other modal forms). before opening <code>Form2</code> I'm setting a timer, that will programmatically close all active modal forms (<code>Form2.Close</code>) and open a new modal <code>Form3</code>.</p>

<p>problem is that when <code>Form3</code> is opening modally, <code>Form2</code> remains (visible) and only when I close <code>Form3</code> by clicking the <code>X</code> will <code>Form2</code> close.</p>

<p>To reproduce add 3 forms to a project add a <code>TButton</code>, and drop a <code>TTimer</code> on <code>Form1</code> (main form):</p>

<pre><code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Timer1: TTimer;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
  public
  end;

var
  Form1: TForm1;

implementation

uses Unit2, Unit3;

{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
begin
  Timer1.Enabled := False;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Timer1.Enabled := True;
  with TForm2.Create(Application) do
  try
    ShowModal;
  finally
    Free;
  end;
end;

procedure CloseActiveModalForms;
var
  I: Integer;
  F: TCustomForm;
  L: TList; // list of modal forms
begin
  L := TList.Create;
  try
    for I := 0 to Screen.CustomFormCount - 1 do
    begin
      F := Screen.CustomForms[I];
      if (fsModal in F.FormState) then
        L.Add(F);
    end;
    for I := 0 to L.Count - 1 do
      TCustomForm(L.Items[I]).Close; // this sets ModalResult := mrCancel
  finally
    L.Free;
  end;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Timer1.Enabled := False;
  CloseActiveModalForms; // this should close TForm2 but it does not.

  with TForm3.Create(Application) do // create new Modal TForm3
  try
    ShowModal;
  finally
    Free;
  end; 
end;

end.
</code></pre>

<p>why <code>Form2</code> is not closing? why is the <code>Form2</code> modal loop not exiting after I call <code>CloseActiveModalForms</code>?</p>