We help IT Professionals succeed at work.

Detect existence of an object

LeTay
LeTay asked
on
Medium Priority
114 Views
Last Modified: 2019-11-10
Is there an easy and elegant way to detect if a specific object has been created ?
In my case, objects to verify are forms.
Thanks
Comment
Watch Question

Sinisa VukSoftware architect
CERTIFIED EXPERT
Top Expert 2012

Commented:
If  you wan to search under parent window (ex. specific panel):
obj: TComponent;
...
obj := pnl1.FindChildControl('Comp1Name');
if Assigned(obj) then ....

Open in new window


if you need to serch on whole form:
obj := FindGlobalComponent('Form1.Comp1Name');
if Assigned(obj) then ....

Open in new window


or

obj := Form1.FindComponent('Comp1Name');
if Assigned(obj) then ....

Open in new window

Author

Commented:
Well in fact, the component I am trying to find if it still exists is that Form1, not a component inside it
So ?
Ferruccio AccalaiSenior developer, analyst and customer assistance
CERTIFIED EXPERT

Commented:
So you can check if it's assigned by
If Assigned(Form1)

Open in new window

or using it's name
var 
  Form: TForm;
begin
  Form := Application.FindComponent('Form1') as TForm;
  if Assigned(Form) then
    Form.Show
  else
    { can't find it, so maybe you want to create it } 

Open in new window

Author

Commented:
My idea was something like this, but it is not very elegant (I know that my forms have their Tag >= 0)

function FormExists(F:TForm):boolean;
begin
  try
    Result := (F.Tag >= 0);
  except
    Result := False;
  end;
end;
Sinisa VukSoftware architect
CERTIFIED EXPERT
Top Expert 2012

Commented:
Form can be found using by Name or using Forms Caption + Class name:

if FindWindow('TForm1', 'FormsCaption') <> 0 then .... // form exists

Open in new window


or using Application as form owner:
...Application.FindComponent('Form1')...

Open in new window

Author

Commented:
Is it faster than "my" method ?
I have to check existence of around a hundred forms ...

Author

Commented:
Also, does the findcomponent return "false" if the form has not been created ?
Software architect
CERTIFIED EXPERT
Top Expert 2012
Commented:
It is easy to check:

function FormExists(FName: String):boolean;
begin
    Result := Assigned(Application.FindComponent(FName));
end; 

Open in new window

Author

Commented:
Many thanks, this works fine

Explore More ContentExplore courses, solutions, and other research materials related to this topic.