Is the form open?

I used the following code to check if the form exists:

function FormExists(apForm: TObject): boolean; var i: Word; begin Result := False; for i := 0 to Application.ComponentCount-1 do if Application.Components[i] = apForm then begin Result := True; Break; end; end; 

I got it a few years ago from a project in which I participated. This was one of my first Delphi projects.

He works.

But this week I wandered around if there is a better and faster way to do this.

+6
source share
2 answers

You can use Screen.Forms instead . It reduces the number of elements you repeat:

 function FormExists(apForm: TForm): boolean; var i: Word; begin Result := False; for i := 0 to Screen.FormCount - 1 do if Screen.Forms[i] = apForm then begin Result := True; Break; end; end; 

However, it is worth noting that if you already have apForm , you know that it exists, and there is no need to look for it.

+12
source

I have found that the best way to do this is to ask the form if it is open. You can do this with the CLASS procedure / function. It is safe to call a class procedure / form function, even if it does not exist.

add a class function to your public desclaration form.

  type TForm2 = class(TForm) ... private { Private declarations } ... public { Public declarations } class function FormExists: Boolean; end; class function TForm2.FormExists: Boolean; var F: TForm2; I: Integer; begin F := nil; for i := Screen.FormCount - 1 DownTo 0 do if (Screen.Forms[i].Name = 'Form2') then begin F := Screen.Forms[I] As TForm2; break; end; Result := F <> nil; end; 

So, from any unit that has the form 2 in the uses clause, you can call

  if Form2.FormExists then ... 
-4
source

Source: https://habr.com/ru/post/922785/


All Articles