【问题标题】:Delphi update a parent form control from a child formDelphi 从子窗体更新父窗体控件
【发布时间】:2014-01-24 00:11:18
【问题描述】:

从一个表单,我创建并显示第二个表单。从第二个表单我想更新第一个表单上的控件。但我得到访问冲突。我可以让它与自动创建中的表单一起使用,但当我使用 create 方法创建表单时,我会遇到违规行为。

下面是一个例子。如果我在自动创建中使用表单 11 运行它,它可以工作(我更新第一个表单中的按钮标题)。但是,如果在第 10 单元中,如果我注释掉 form11.show;,并且我取消注释创建和显示,然后从自动创建中取出 Form11,我会遇到访问冲突。

问题 - 当我使用 create 方法创建表单时,如何从显示的表单更新父表单。

单元10

unit Unit10;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
type
  TForm10 = class(TForm)
     Button1: TButton;
     procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
  Form10: TForm10;
implementation
uses Unit11;
{$R *.dfm}
procedure TForm10.Button1Click(Sender: TObject);
var
  fForm     : TForm11;
Begin
//        fForm := Form11.Create(Self);  //This and next line give me access violation
//        fForm.Show;           //   with form11 out of autocreate
   form11.show;            //This works with form11 in the autocreate.
end;
end.

单元 11

unit Unit11;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
type
  TForm11 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
var
  Form11: TForm11;
implementation
uses unit10;
{$R *.dfm}
procedure TForm11.Button1Click(Sender: TObject);
begin
form10.button1.caption := 'Changed';
end;
end.

【问题讨论】:

    标签: delphi


    【解决方案1】:

    这是不正确的:

    fForm := Form11.Create(Self)
    

    应该是这样的:

    fForm := TForm11.Create(Self)
    

    TForm11,而不是Form11。要创建对象,必须通过类调用构造函数。

    【讨论】:

      【解决方案2】:

      我一直只是让我的表单自动创建并且想不出不这样做的理由,但是这可能是您的问题的原因:
      Create 方法需要在类上调用,而不是在变量上。

      这一行可能会创建一个新的 TForm11 实例:

      
          fForm := TForm11.Create(Self);
      

      【讨论】:

      • 一般来说,您不应该自动创建除 MainForm 之外的任何表单。而是根据需要动态创建表单。它加快了应用的启动速度,并且更好地减少了内存使用。
      • 不自​​动创建表单的原因可能有四打。内存使用、启动缓慢和浪费的 CPU 周期是立即浮现在脑海中的三个。我总是在新的 Delphi 安装中做的第一件事是转到 Tools->Options->VCL Designer(较新版本的 Form Designer)并取消选中“Auto-create forms and data modules”。
      猜你喜欢
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2020-10-12
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      相关资源
      最近更新 更多