Delphi应用程序架构中有一种模式,采用DLL或Package存储业务窗体,当需要时从其中载入到主程序中,这时候需要对DLL或Package中窗体进行处理,步骤如下:
1、定义窗体基类
type
TfrmBase = class(TForm)
Panel1: TPanel;
private
{ Private declarations }
protected
procedure Loaded;override;
public
{ Public declarations }
procedure UpdateActions; override;
end;
TfrmBaseClass = class of TfrmBase;
implementation
{$R *.dfm}
{ TfrmBase }
procedure TfrmBase.Loaded;
begin
inherited;
//将窗体改变为嵌入化
align := alClient;
BorderStyle := bsNone;
BorderIcons := [];
end;
procedure TfrmBase.UpdateActions;
begin
inherited;
//将方法Public化
end;
2、创建具体的实例窗体
TfrmDll = class(TfrmBase)
3、通过窗体数据窗体类
function GetDllFormClass : TfrmBaseClass;
begin
Result := TfrmDll;
end;
exports
GetDllFormClass;
4、主窗体中动态载入DLL和创建DLL中的窗体对象
procedure TfrmMain.Button1Click(Sender: TObject);
begin
if DllHandle > 0 then
Exit;
DllHandle := LoadLibrary('FormDll.dll');
if DllHandle > 0 then
begin
GetDllFormClass := GetProcAddress(DllHandle, 'GetDllFormClass');
ifAssigned(GetDllFormClass) then
begin
cfrm := GetDllformClass;
vfrm := cfrm.Create(Application);
//设置窗体的Parent,通过ParentWindow方法实现,这点很重要
vfrm.ParentWindow := TabSheet1.Handle;
end;
end;
end;
5、在主窗体上放置一个TApplicationEvents控件,在OnIdle事件中填写以下代码:
procedure TfrmMain.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
begin
//当系统空闲时,处理子窗体的ActionUpdate事件
if Assigned(vfrm) then
vfrm.UpdateActions;
end;
6、在OnMessage事件中填写以下代码:
procedure TfrmMain.ApplicationEvents1Message(var Msg: tagMSG;
var Handled: Boolean);
begin
//如果窗体变量存在,则需要对消息进行判断和处理,如果是窗体变量的消息,则不进一步处理
if Assigned(vfrm) then
begin
if IsDialogMessage(vfrm.Handle, Msg) then
Handled := true;
end;
end;
至此完成。