Difference between revisions of "Testing, if form exists"

From Free Pascal wiki
(I think you meant forum discussions ;) Thanks for the page!)
m
Line 15: Line 15:
 
begin
 
begin
 
   for I := 0 to Screen.FormCount -1 do
 
   for I := 0 to Screen.FormCount -1 do
     if Screen.Forms[vCnt].ClassType = aClass then begin
+
     if Screen.Forms[I].ClassType = aClass then begin
 
       Result := Screen.Forms[I];
 
       Result := Screen.Forms[I];
 
       Break;
 
       Break;
Line 31: Line 31:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Use CloseACtion := caFree in the form onClose event.
+
Use CloseACtion := caFree in the form's OnClose event.
  
 
[[Category:Code]]
 
[[Category:Code]]
 
[[Category:LCL]]
 
[[Category:LCL]]
 
[[Category:Forms]]
 
[[Category:Forms]]

Revision as of 00:32, 19 November 2013

Sometimes a form may be launched from several places in a program. If it already exists, it only needs to be brought to the front. If not, it needs to be created.

One way to do this is to use a global boolean variable which is set to true or false as the form is created or destroyed.

Another way is to use a function as below.

These functions are copied from forum discussions.

How to list all data modules opened in an Application? [1]

function FindForm(const aClass:TClass):TForm;
var
  I: Integer;
begin
  for I := 0 to Screen.FormCount -1 do
    if Screen.Forms[I].ClassType = aClass then begin
      Result := Screen.Forms[I];
      Break;
    end;
end;

Call it with:

if FindForm(TMyForm) <> nil then MyForm.Show
else 
begin
  MyForm := TMyForm.Create(Application);
  MyForm.Show;    
end;

Use CloseACtion := caFree in the form's OnClose event.