Author: Tomas Rutkauskas
How to check if a TForm has already been created
Answer:
Solve 1:
You just need to provide a little code to manage the lifetime of the form.
Something like this (which assumes there should only ever be one instance of the
TForm1 class):
1 interface2 3 procedure ShowForm;
4 procedure CloseForm;
5 6 implementation7 8 var9 Form: TForm1;
10 11 procedure ShowForm;
12 begin13 if (Form <> nil) then14 Form.Show
15 else16 begin17 Form := TForm1.Create(Application);
18 Form.Show;
19 end;
20 end;
You can only check for nil the first time, because once you create and free the
form it won't be nil again unless you make it nil in code!
21 procedure CloseForm;
22 begin23 Form.Free;
24 Form := nil;
25 end;
Then simply call these help functions whenever you want to show or close the form.
Solve 2:
You can use the FindWindow API function, but for checking if a form has been
created within an application, this is easier:
26 function IsFormCreated(Form: TCustomForm): Boolean;
27 var28 i: Integer;
29 begin30 Result := False;
31 for i := 0 to Screen.FormCount - 1 do32 begin33 if Screen.Forms[i] = Form then34 begin35 Result := True;
36 Break;
37 end;
38 end;
39 end;
Solve 3:
Know whether a form already exist before I dynamically create it
40 function IsFormOpen(const FormName: string): Boolean;
41 var42 i: Integer;
43 begin44 Result := False;
45 for i := Screen.FormCount - 1 downto 0 do46 if (Screen.Forms[i].Name = FormName) then47 begin48 Result := True;
49 Break;
50 end;
51 end;
52 53 //First check, if the Form (here Form2) is open. If not, create it. 54 55 procedure TForm1.Button1Click(Sender: TObject);
56 begin57 ifnot IsFormOpen('Form2') then58 Form2 := TForm2.Create(Self);
59 60 Form2.Show
61 end;
62 63 { For MDI Children }64 65 function IsMDIChildOpen(const AFormName: TForm; const AMDIChildName: string):
66 Boolean;
67 var68 i: Integer;
69 begin70 Result := False;
71 for i := Pred(AFormName.MDIChildCount) downto 0 do72 if (AFormName.MDIChildren[i].Name = AMDIChildName) then73 begin74 Result := True;
75 Break;
76 end;
77 end;
78 79 //First check, if the MDI Child is open. If not, create it. 80 81 procedure TForm1.Button2Click(Sender: TObject);
82 begin83 ifnot IsMDIChildOpen(Form1, 'MyMDIChild') then84 MyMDIChild := TMyMDIChild.Create(Self);
85 MyMDIChild.Show;
86 MyMDIChild.BringToFront;
87 end;