无法在模式窗体上从 FormCreate 调用的过程中访问 VCL 组件(即直接在打开窗体后)

Cannot access a VCL component in a procedure called from FormCreate on a modal form (i.e. directly after opening the form)

运行 当我打开模态窗体 (Form2) 时出现运行时错误,该窗体在创建时调用另一个对 VCL 组件执行某些操作的过程。下面的程序演示了这个问题。

这是模态形式的代码:

procedure DoLabel;
begin
  form2.Label1.Caption := 'A';
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  DoLabel;
end;

这编译得很好。但是,程序在打开模态窗体时崩溃。调试器说:地址 xxxx 处的访问冲突。这可能是一个基本错误,但我做错了什么?以及如何解决这个问题?

您正在使用全局 Form2 变量,该变量尚未分配(或根本没有分配),而 TForm2 对象仍在构造中。

您需要更改您的代码以在构造期间不依赖该变量(最好将其完全删除,除非 TForm2 是在启动时自动创建的,这听起来不像是这样)。

例如,将窗体的Self指针,甚至TLabel指针作为输入参数传递给DoLabel(),例如:

procedure DoLabel(ALabel: TLabel);
begin
  ALabel.Caption := 'A';
end;

procedure DoFormStuff(AForm: TForm2);
begin
  // use AForm as needed...
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  DoLabel(Label1);
  DoFormStuff(Self);
end;

不过,在这种情况下,DoFormStuff() 更有意义,也可能 DoLabel() 成为 TForm2 class 的成员,而不是免费功能:

procedure TForm2.FormCreate(Sender: TObject);
begin
  DoLabel;
  DoFormStuff;
end;

procedure TForm2.DoLabel;
begin
  Label1.Caption := 'A';
end;

procedure TForm2.DoFormStuff;
begin
  // use Self as needed...
end;