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 27 function IsFormCreated(Form: TCustomForm): Boolean;
28 var29 i: Integer;
30 begin31 Result := False;
32 for i := 0 to Screen.FormCount - 1 do33 begin34 if Screen.Forms[i] = Form then35 begin36 Result := True;
37 Break;
38 end;
39 end;
40 end;
Solve 3:
Know whether a form already exist before I dynamically create it
41 42 function IsFormOpen(const FormName: string): Boolean;
43 var44 i: Integer;
45 begin46 Result := False;
47 for i := Screen.FormCount - 1 downto 0 do48 if (Screen.Forms[i].Name = FormName) then49 begin50 Result := True;
51 Break;
52 end;
53 end;
54 55 //First check, if the Form (here Form2) is open. If not, create it. 56 57 procedure TForm1.Button1Click(Sender: TObject);
58 begin59 ifnot IsFormOpen('Form2') then60 Form2 := TForm2.Create(Self);
61 62 Form2.Show
63 end;
64 65 { For MDI Children }66 67 function IsMDIChildOpen(const AFormName: TForm; const AMDIChildName: string):
68 Boolean;
69 var70 i: Integer;
71 begin72 Result := False;
73 for i := Pred(AFormName.MDIChildCount) downto 0 do74 if (AFormName.MDIChildren[i].Name = AMDIChildName) then75 begin76 Result := True;
77 Break;
78 end;
79 end;
80 81 //First check, if the MDI Child is open. If not, create it. 82 83 procedure TForm1.Button2Click(Sender: TObject);
84 begin85 ifnot IsMDIChildOpen(Form1, 'MyMDIChild') then86 MyMDIChild := TMyMDIChild.Create(Self);
87 MyMDIChild.Show;
88 MyMDIChild.BringToFront;
89 end;