简体   繁体   English

检查对象是否在delphi中创建

[英]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. 我正在使用Delphi 7构建一个应用程序。我在主窗体上添加了一个按钮。 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? Form对象是否具有任何属性,我们可以通过该属性直接检查它是否已创建?

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 . 但是如果您的表单在 全局 声明,则必须确保将其初始化为nil

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;

Assigned(Obj) can still return True even after you free it, using "Obj.free". 即使在你使用“Obj.free”释放后,Assigned(Obj)仍然可以返回True。 The best way to assure your obj is free, FOR USING Assigned(obj) is using "FreeAndNil(Obj)" 确保你的obj是免费的最好方法,FOR USING Assigned(obj)正在使用“FreeAndNil(Obj)”

Sometimes form has been free but it is not nil. 有时形式是免费的,但它不是零。 In such case the check of Assigned is not so good. 在这种情况下,Assigned的检查不太好。 So one option is to free the form and set MyForm:=nil on OnClose form. 因此,一种选择是释放表单并在OnClose表单上设置MyForm:= nil。 another option is to use the following proc: 另一个选择是使用以下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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM