所有窗体单元都应当含有实例化函数,用于创建、设置、模式显示和释放窗体。这个函数将返回由窗体返回的模式结果。传递给这个函数的参数遵循参数传递的规则。之所以要这样封装,是为了便于代码的重用和维护。
窗体的变量应当从单元中移走,改在窗体实例化函数中作为局部变量定义(注意,要求从Project Options对话框的自动生成列表中移走该窗体。请看前面的内容。
例如,下面的单元文件演示了GetUserData的实例化函数。
Unit UserDataFrm;
Inte***ce
Uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
Type
TfrmUserData = class(TForm)
edtUserName: TEdit;
edtUserID: TEdit;
private
{ Private declarations }
public
{ Public declarations }
end;
function GetUserData(var aUserName: String;var aUserID: Integer): Word;
implementation
{$R *.DFM}
function GetUserData(var aUserName: String;var aUserID: Integer): Word;
var
frmUserData: TfrmUserData;
begin
frmUserData := TfrmUserData.Create(Application);
frmUserData.Caption:='Getting User Data' ;
Result : = frmUserData.ShowModal;
if Result=mrOK then
begin
aUserName := frmUserData.edtUserName.Text;
aUserID := StrToInt(frmUserData.edtUserID.Text);
end;
finally
frmUserData.Free;
end;
end;
End.
窗体的变量应当从单元中移走,改在窗体实例化函数中作为局部变量定义(注意,要求从Project Options对话框的自动生成列表中移走该窗体。请看前面的内容。
例如,下面的单元文件演示了GetUserData的实例化函数。
Unit UserDataFrm;
Inte***ce
Uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
Type
TfrmUserData = class(TForm)
edtUserName: TEdit;
edtUserID: TEdit;
private
{ Private declarations }
public
{ Public declarations }
end;
function GetUserData(var aUserName: String;var aUserID: Integer): Word;
implementation
{$R *.DFM}
function GetUserData(var aUserName: String;var aUserID: Integer): Word;
var
frmUserData: TfrmUserData;
begin
frmUserData := TfrmUserData.Create(Application);
frmUserData.Caption:='Getting User Data' ;
Result : = frmUserData.ShowModal;
if Result=mrOK then
begin
aUserName := frmUserData.edtUserName.Text;
aUserID := StrToInt(frmUserData.edtUserID.Text);
end;
finally
frmUserData.Free;
end;
end;
End.
![](https://i-blog.csdnimg.cn/blog_migrate/7a9f8c2f833206445a63e9b8dc5b1286.gif)