首先点击File->New->Other-> Dynamic Link Libary
把工程文件保存为:CalendarLib.pas 再创建一个Form并放入一个TMonthCalendar控件
borderStyle属性设为:bsToolWindow
保存为 DllFormUnit.pas
unit
DllFormUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls;
type
TDllForm =
class
(TForm)
MonthCalendar1: TMonthCalendar;
procedure
MonthCalendar1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end
;
var
DllForm: TDllForm;
|
// 供外部调用函数
|
function
ShowCalendar(AHandle: THandle;ACaption:
String
):
PChar
;stdcall;
|
implementation
{$R *.dfm}
function
ShowCalendar(AHandle: THandle;ACaption:
String
):
PChar
;
var
DllForm: TDllForm;
begin
//复制应用程序的句柄给Dll
//Dll中Application对象与调用它的应用程序是分离的,为使Dll中的窗体真正的成
//为应用程序模式窗体,必须将应用程序的句柄赋给Dll的Application.Handle属性
//必须确保AHandle句柄不为nil,否则出现无法预料的错误
Application
.
Handle := AHandle;
DlLForm := TDllForm
.
Create(Application);
try
DllForm
.
Caption := ACaption;
DllForm
.
ShowModal;
Result :=
PChar
(DateToStr(DllForm
.
MonthCalendar1
.
Date));
finally
DllForm
.
Free;
end
;
end
;
procedure
TDllForm
.
MonthCalendar1Click(Sender: TObject);
begin
Close;
end
;
end
.
|
CalendarLib.pas
library
CalendarLib;
uses
SysUtils,
Classes,
DllFormUnit
in
'DllFormUnit.pas'
{DllForm}
;
{$R *.res}
exports
ShowCalendar;
begin
end
.
|
主窗体设计
MainFormUnit.pas文件
unit MainFormUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TShowCalendar = function (AHandle: THandle;ACaption: String):PChar;stdcall;
TMainForm = class(TForm)
btnShowCalendar: TButton;
lblDate: TLabel;
procedure btnShowCalendarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.btnShowCalendarClick(Sender: TObject);
var
ShowCalendarForm: TShowCalendar;
libHandle: THandle;
begin
libHandle := LoadLibrary('CalendarLib.dll');
try
//是否读取成功
if libHandle = 0 then
raise Exception.Create('加载CalendarLib.dll失败');
//读取函数方法地址
@ShowCalendarForm := GetProcAddress(LibHandle,'ShowCalendar');
//读取是否成功
if not (@ShowCalendarForm = nil) then
begin
lblDate.Caption :=ShowCalendarForm(Application.Handle,'选择日历');
end
else
RaiseLastWin32Error;
finally
//释放Dll
FreeLibrary(LibHandle);
DFM文件
object MainForm: TMainForm
Left = 0
Top = 0
Caption = 'MainForm'
ClientHeight = 202
ClientWidth = 447
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object lblDate: TLabel
Left = 119
Top = 45
Width = 98
Height = 13
Caption = #26085#26399':'
end
object btnShowCalendar: TButton
Left = 16
Top = 40
Width = 97
Height = 25
Caption = #26174#31034#26085#21382#31383#20307
TabOrder = 0
OnClick = btnShowCalendarClick
end
end
运行结果: