前天遇到一個疑問:主表單是fsMDIForm時,調用DLL的表單不可以嵌入在主表單中。於是就這個問題,我在網上找了相關資料,並找到答案:DLL封裝子表單。
瞭解後,使用相同方法在DLL的子表單再調用另一個DLL表單也可以。如果需要回傳參數,可以通過函數獲得。
執行個體如下:
新增Dll Application,在工程中建立一個Form,現在這個Dll就是擁有表單的DLL了。
DLL中的代碼:
library Project2;
{ Important note about DLL memory management: ShareMem must be the
first unit in your library's USES clause AND your project's (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings as parameters or function results. This
applies to all strings passed to and from your DLL--even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be deployed along
with your DLL. To avoid using BORLNDMM.DLL, pass string information
using PChar or ShortString parameters. }
uses
SysUtils,
Classes,
Forms,
Windows,
Messages,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
var
DLLApp: TApplication;
function ShowForm(var App: TApplication;ParentForm: TForm): Boolean;export; stdcall;
begin
{擷取調用表單的Application,顯而易見的功能是 能使你的表單融合到調用程式中。通過它還能進行很多操作}
Application:= App;//將DLL的Application轉為App
Form1:= TForm1.Create(ParentForm);//建立子表單,子表單隨著ParentForm存在、釋放。
Form1.FormStyle:= fsMDIChild;//設定表單模式
Form1.Show;
end;
{重寫Dll入口函數,否則程式會出錯}
procedure DLLUnloadProc(Reason: Integer); register;
begin
{DLL取消調用時,發送DLL_PROCESS_DETACH訊息,此時將DLL的Application返回為本身}
if Reason = DLL_PROCESS_DETACH then Application:=DLLApp;
end;
exports
ShowForm;
begin
{在DLL入口預先儲存DLL的Application}
DLLApp:=Application;
{DllProc:DLL入口函數指標。Delphi定義為 DllProc: TDLLProc;}
{在此指向我們自己定義的函數}
DLLProc := @DLLUnloadProc;
end.
調用主程式單元,只需要一個TButton 就可以。
unit Unitmain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, Menus, ToolWin, RzPanel, cxControls, cxContainer,
cxTreeView, dxNavBar, dxDockPanel, dxDockControl, ExtCtrls, RzSplit;
type
TForm1 = class(TForm)
mm1: TMainMenu;
N1: TMenuItem;
pnl1: TPanel;
fsMDIChild1: TMenuItem;
DLL1: TMenuItem;
procedure DLL1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
function ShowForm(var App: TApplication; ParentForm: TForm): Boolean;stdcall; external 'Project2.dll';//為了簡單,使用靜態調用方法
implementation
{$R *.dfm}
procedure TForm1.DLL1Click(Sender: TObject);
begin
ShowForm(Application, Self);//調用DLL函數調出表單。傳入當前主程式的Application對象和Form1本身
end;
end.