2014-01-24 85 views
-1

從窗體創建並顯示第二個窗體。從第二種形式,我想更新第一種形式的控件。但是我得到訪問違規。我可以讓它與自動創建中的表單一起工作,但不是當我使用create方法創建表單時,我得到了違規。Delphi從子窗體更新父窗體控件

下面是一個例子。如果我在自動創建時使用表單11的方式運行它(我更新第一個表單中的按鈕標題)。但是,如果在單元10中,如果我註釋掉form11.show;並且我取消註釋創建和顯示,然後將Form11從自動創建中除去,則會出現訪問衝突。

問題 - 當我使用create方法創建表單時,如何從顯示的表單更新父表單。

Unit10

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. 

Unit11

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. 

回答

7

這是不正確的:

fForm := Form11.Create(Self) 

它應該是這樣的:

fForm := TForm11.Create(Self) 

TForm11,而不是Form11。要創建一個對象,你必須通過類調用構造函數。

2

我一直有我的表單自動創建,不能想到一個理由不這樣做,但這是你的問題的可能原因:
Create方法需要在一個類上調用,不在變量上。

該行可能會努力創造TForm11的新實例:


    fForm := TForm11.Create(Self); 
+4

一般情況下,你不應該自動創建不是MainForm的其他任何形式。改爲根據需要動態創建您的表單。它加快了你的應用程序的啓動速度,而且對內存使用情況更好。 –

+5

可能有四十幾個原因不能自動創建表單。內存使用,啓動速度慢,CPU週期浪費是立即想到的三個問題。我總是在新的Delphi安裝上做的第一件事是去工具 - >選項 - > VCL設計器(新版本的表單設計器),並取消選中「自動創建表單和數據模塊」。 –

相關問題