delphi窗体变量如何调用窗体中相关的组件!晕了!
delphi窗体变量怎么调用窗体中相关的组件!急晕了!!!!!!!!!!!!!!!!!!!!!
各位请教,如题。如下意思:我创建了一个全局变量CurFor:Tform; 在打开一个FORM1时将CurFor=FORM1;在打开FORM2时调用FORM1中BUTTON组件 CurFor.BUTTON1.CAPTION时代码错误提示: undeclared identifier:''BUTTON1‘!!!
请都是什么原因,CurFor.CAPTION为什么能看到FORM1中CAPTION正确信息。或在FORM2中FORM1.BUTTON1.CAPTION也没问题??????
------解决思路----------------------
1、定义全局中变量
var CurFor:Tform;
CurFor仅是可以指向中Tform对象的一个指针而已。
2、在Form1中,虽然
CurFor:=Form1; 它是指向了Form1实体。但是Form1实体它包含的内容(控件)是未知的。
3、为了能正确引导出Form1实体,需要通过
TFORM1(CurFor),强制转换。这样才能引导出Form1。
代码如下:
Unit1为Form1:
Unit2为Form2:
Unit3定义全局变量。
------解决思路----------------------
可以采用这么做,也不需要引用其他窗体
var
CurFor: TForm;
...
CurFor := Form1;
...
if TForm(CurFor).FindComponent('BUTTON1')<>nil then
begin
TButton(TForm(CurFor).FindComponent('BUTTON1')).Caption := 'clik me';
end;
各位请教,如题。如下意思:我创建了一个全局变量CurFor:Tform; 在打开一个FORM1时将CurFor=FORM1;在打开FORM2时调用FORM1中BUTTON组件 CurFor.BUTTON1.CAPTION时代码错误提示: undeclared identifier:''BUTTON1‘!!!
请都是什么原因,CurFor.CAPTION为什么能看到FORM1中CAPTION正确信息。或在FORM2中FORM1.BUTTON1.CAPTION也没问题??????
------解决思路----------------------
1、定义全局中变量
var CurFor:Tform;
CurFor仅是可以指向中Tform对象的一个指针而已。
2、在Form1中,虽然
CurFor:=Form1; 它是指向了Form1实体。但是Form1实体它包含的内容(控件)是未知的。
3、为了能正确引导出Form1实体,需要通过
TFORM1(CurFor),强制转换。这样才能引导出Form1。
代码如下:
Unit1为Form1:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses unit3,unit2;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage('Form1');
end;
procedure TForm1.FormShow(Sender: TObject);
begin
CurFor:=Form1;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Form2.show;
end;
end.
Unit2为Form2:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm2 = class(TForm)
Button1: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
uses unit1,unit3;
procedure TForm2.Button1Click(Sender: TObject);
begin
Edit1.text:=TFORM1(CurFor).BUTTON1.CAPTION;
end;
end.
Unit3定义全局变量。
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
var CurFor:Tform;
implementation
end.
------解决思路----------------------
可以采用这么做,也不需要引用其他窗体
var
CurFor: TForm;
...
CurFor := Form1;
...
if TForm(CurFor).FindComponent('BUTTON1')<>nil then
begin
TButton(TForm(CurFor).FindComponent('BUTTON1')).Caption := 'clik me';
end;