Delphi 用DLL实现插件的简单实例
Delphi用DLL实现插件的简单实例
这是DLL的代码
实现代码:
libraryMyDll; uses SysUtils, Dialogs, Classes; procedureShowInfo(info:PChar);stdcall; begin ShowMessage('您选择了【'+info+'】'); end; functionGetCaption:Pchar; begin Result:='中国'; end; exportsShowInfo, GetCaption; {$R*.res} begin end.
这是调用窗体的代码
本例只使用了一个DLL,所以当有多个DLL时,需要循环DLL所在目录,依次加载DLL
unitMain; interface uses Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms, Dialogs,StdCtrls,Menus,ExtCtrls; type TShowInfo=procedure(info:PChar);stdcall; TGetCaption=function:PChar;stdcall; TForm1=class(TForm) Button1:TButton; Button2:TButton; MainMenu1:TMainMenu; Image1:TImage; procedureButton2Click(Sender:TObject);private {Privatedeclarations} FHandel:THandle;//DLL句柄 FProAddress:Pointer;//DLL中ShowInfo的地址 showinfo:TShowInfo;//为动态加载DLL而设 procedureLoadPlusIn;//加载插件(DLL) procedureItemClick(Sender:TObject);//自定义菜单点击事件 public {Publicdeclarations} end; var Form1:TForm1; implementation {$R*.dfm} procedureTForm1.Button2Click(Sender:TObject); begin LoadPlusIn; end; procedureTForm1.ItemClick(Sender:TObject); begin @showinfo:=FProAddress;//取地址 if@showinfo<>nilthen showinfo(PWideChar(TMenuItem(Sender).Caption));//执行DLL中的ShowInfo end; procedureTForm1.LoadPlusIn; var getcaption:TGetCaption; item:TMenuItem; begin FHandel:=LoadLibrary('MyDll.dll');//加载 ifFHandel=0then begin ShowMessage('加载失败!'); Exit; end else begin @getcaption:=GetProcAddress(FHandel,'GetCaption');//取DLL中GetCaption地址 if@getcaption<>nilthen begin item:=TMenuItem.Create(MainMenu1);//创建一个菜单 item.Caption:=getcaption;//取Caption,即调用DLL中的GetCaption FProAddress:=GetProcAddress(FHandel,'ShowInfo');//取得DLL中ShowInfo的地址 item.OnClick:=ItemClick;//赋予菜单项的点击事件 MainMenu1.Items.Add(item);//添加到主菜单 end; end; end; end.
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!