在一个Form 中控制另一个form 中的控件(50分)

  • 主题发起人 主题发起人 plzh
  • 开始时间 开始时间
P

plzh

Unregistered / Unconfirmed
GUEST, unregistred user!
这个问题一直困扰着我。
三个form, form1,form2,form3,其中form1 为主窗口,form2,form3属于
available forms.
在form1中打开form2,在form2 中打开form3,在form3中更改form2中Tlabel
的caption.每次运行到更改语句时出错。请指教我怎样才能达到目的。
代码如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
uses unit2;
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
Form2:TForm2;
begin
Form2:=TForm2.Create(self);
Form2.Show;
end;

unit Unit2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm2 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form2: TForm2;
implementation
uses unit3;
{$R *.DFM}
procedure TForm2.Button1Click(Sender: TObject);
var
Form3:tFORM3;
begin
Form3:=TForm3.create(self);
Form3.show;
end;

end.

unit Unit3;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm3 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form3: TForm3;
implementation
uses unit2;
{$R *.DFM}
procedure TForm3.Button1Click(Sender: TObject);
begin
Form2.label1.caption:='hsdfhdsf';//在此出现错误
end;

end.
 
我试过.没问题.
另外,form create 应检查是否有实例存在
{ Check if instance of for exists }
if not Assigned(Modeless) then
{ Create the form instance }
Modeless := TModeless.Create(Application);
Modeless.Show;
// Show form as modeless, in this case the form
form 关闭时应删除form实例
procedure TModeless.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
// Free the form instance when closed
end;

procedure TModeless.FormDestroy(Sender: TObject);
begin
Modeless := nil;
// Set the NonModalForm variable to nil when destroyed.
end;
 
在Form1中建立的Form2是局部变量。与Form3中引用的不是一个Form,
procedure TForm1.Button1Click(Sender: TObject);
var
Form2:TForm2;
//将此变量放到可声明全局变量处,即可。
begin
Form2:=TForm2.Create(self);

Form2.Show;
end;
 
這是全局變量与局部變量問題
form2定義的FORM2屬于局部變量
FORM3使用FORM2時FORM2=NIL.
要解決這個問,可把FORM2定義為全局量即可.
 
这样做啃腚不行,因为你再form1上再点button1又会有form2到时调哪个form2?
 
agree谭俊峰
 
這是全局變量与局部變量問題
form2定義的FORM2屬于局部變量
FORM3使用FORM2時FORM2=NIL.
要解決這個問,可把FORM2定義為全局量即可.
 
多人接受答案了。
 
后退
顶部