Mirror

How to create only one instance of a MDI child form (4) (Views: 100)


Problem/Question/Abstract:

What is the best way to avoid a form being created more than once in a MDI application?

Answer:

unit WindowFunctions;

interface

uses
  Classes, Forms;

function IsChildWindow(AFormClass: TFormClass; AiTag: integer): Boolean;
procedure CreateChildWin(AOwner: TComponent; AFormClass: TFormClass; AiTag: integer);

implementation

uses
  Dialogs, Controls;

function IsChildWindow(AFormClass: TFormClass; AiTag: integer): boolean;
var
  i: integer;
begin
  Result := False; {The window does not exist}
  for i := 0 to (Screen.FormCount - 1) do
  begin
    if (Screen.Forms[i] is AFormClass) and (AiTag = Screen.Forms[i].Tag) then
    begin
      {The window was found}
      Screen.Forms[i].BringToFront;
      Result := True;
      break;
    end;
  end;
end;

procedure CreateChildWin(AOwner: TComponent; AFormClass: TFormClass; AiTag: integer);
begin
  if not IsChildWindow(AFormClass, AiTag) then
  begin
    with AFormClass.Create(AOwner) do
    begin
      Tag := AiTag;
    end;
  end;
end;

end.

<< Back to main page