naren
naren

Reputation: 629

check if the object is created or not in delphi

I am building an application using Delphi 7. I have added one button on the main form. On that button click I want to show another form. I am trying to create a second form only if the user has clicked that button for the first time. If the user clicks that button a second time then already created form should be displayed. Does a Form object have any property through which we can directly check if it is already created or not?

Upvotes: 11

Views: 30103

Answers (4)

Yos863
Yos863

Reputation: 31

Sometimes form has been free but it is not nil. In such case the check of Assigned is not so good. So one option is to free the form and set MyForm:=nil on OnClose form. another option is to use the following proc:

function TMyForm.IsFormCreated: bool;
var i: Integer;
begin
  Result := False;
  for i := 0 to Screen.FormCount - 1 do
  begin
    if Screen.Forms[i] is TMyForm then
    begin
      Result := True;
      Break;
    end;
  end;
end;

Upvotes: 3

user1897277
user1897277

Reputation: 495

Assigned(Obj) can still return True even after you free it, using "Obj.free". The best way to assure your obj is free, FOR USING Assigned(obj) is using "FreeAndNil(Obj)"

Upvotes: 3

Linas
Linas

Reputation: 5545

if Assigned(Form1) then
begin
  //form is created
end;

But if your form is declared locally globally you must make sure that it is initialized to nil.

Upvotes: 15

David Heffernan
David Heffernan

Reputation: 612993

You need a member field to hold the reference to the form. Then check whether that reference is assigned. Like this:

function TMainForm.GetOtherForm: TMyForm;
begin
  if not Assigned(FOtherForm) then
    FOtherForm := TMyForm.Create(Self);
  Result := FOtherForm;
end;

Upvotes: 4

Related Questions