Check if a TForm has already been created (Views: 2141)
Problem/Question/Abstract: 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): interface procedure ShowForm; procedure CloseForm; implementation var Form: TForm1; procedure ShowForm; begin if (Form <> nil) then Form.Show else begin Form := TForm1.Create(Application); Form.Show; end; 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! procedure CloseForm; begin Form.Free; Form := nil; 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: function IsFormCreated(Form: TCustomForm): Boolean; var i: Integer; begin Result := False; for i := 0 to Screen.FormCount - 1 do begin if Screen.Forms[i] = Form then begin Result := True; Break; end; end; end; Solve 3: Know whether a form already exist before I dynamically create it function IsFormOpen(const FormName: string): Boolean; var i: Integer; begin Result := False; for i := Screen.FormCount - 1 downto 0 do if (Screen.Forms[i].Name = FormName) then begin Result := True; Break; end; end; First check, if the Form (here Form2) is open. If not, create it. procedure TForm1.Button1Click(Sender: TObject); begin if not IsFormOpen('Form2') then Form2 := TForm2.Create(Self); Form2.Show end; { For MDI Children } function IsMDIChildOpen(const AFormName: TForm; const AMDIChildName: string): Boolean; var i: Integer; begin Result := False; for i := Pred(AFormName.MDIChildCount) downto 0 do if (AFormName.MDIChildren[i].Name = AMDIChildName) then begin Result := True; Break; end; end; First check, if the MDI Child is open. If not, create it. procedure TForm1.Button2Click(Sender: TObject); begin if not IsMDIChildOpen(Form1, 'MyMDIChild') then MyMDIChild := TMyMDIChild.Create(Self); MyMDIChild.Show; MyMDIChild.BringToFront; end; |