查看: 79|回复: 0

[教程] Delphi 用DLL实现插件的简单实例

[复制链接]

0

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2010-9-14
发表于 2017-9-3 16:25:54 | 显示全部楼层 |阅读模式

Delphi 用DLL实现插件的简单实例

这是DLL的代码  

实现代码: 

library MyDll; 
 
uses 
 SysUtils, 
 Dialogs, 
 Classes; 
 
procedure ShowInfo(info:PChar);stdcall; 
begin 
 ShowMessage('您选择了【'+info+'】'); 
end; 
 
function GetCaption:Pchar; 
begin 
 Result := '中国'; 
end; 
 
exports ShowInfo,     
    GetCaption; 
 
{$R *.res} 
 
begin 
end. 

这是调用窗体的代码 

本例只使用了一个DLL,所以当有多个DLL时,需要循环DLL所在目录,依次加载DLL  

unit Main; 
 
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; 
  procedure Button2Click(Sender: TObject); private 
  { Private declarations } 
  FHandel : THandle;   //DLL句柄 
  FProAddress: Pointer; //DLL中ShowInfo的地址 
  showinfo: TShowInfo;  //为动态加载DLL而设 
  procedure LoadPlusIn; //加载插件(DLL) 
  procedure ItemClick(Sender: TObject);  //自定义菜单点击事件 
 public 
  { Public declarations } 
 end; 
 
var 
 Form1: TForm1; 
 
implementation 
 
{$R *.dfm} 
 
procedure TForm1.Button2Click(Sender: TObject); 
begin 
 LoadPlusIn; 
end; 
 
procedure TForm1.ItemClick(Sender: TObject); 
begin 
 @showinfo := FProAddress;   //取地址 
 if @showinfo <> nil then 
  showinfo(PWideChar(TMenuItem(Sender).Caption)); //执行DLL中的ShowInfo 
end; 
 
procedure TForm1.LoadPlusIn; 
var 
 getcaption: TGetCaption; 
 item : TMenuItem; 
begin 
 FHandel := LoadLibrary('MyDll.dll');  //加载 
 if FHandel = 0 then 
 begin 
  ShowMessage('加载失败!'); 
  Exit; 
 end 
 else 
 begin 
  @getcaption := GetProcAddress(FHandel,'GetCaption');  //取DLL中GetCaption地址 
  if @getcaption <> nil then 
  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. 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:
  • Delphi 根据字符串找到函数并执行的实例
  • Delphi 中内存映射对于大文件的使用
  • Delphi提取PDF文本实例
  • Delphi XE5 为Android应用制作签名的方法(图文)
  • ListView 百分比进度条(delphi版)
  • Delphi实现截屏存盘的方法
  • Delphi实现窗体感知鼠标滑过并自动隐藏与显示窗口的方法
  • Delphi 实现软件自动升级的功能
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部