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);dcstall; = class(TForm) Button1: TButton; Button2: TButton; MainMenu1: TMainMenu; Image1: TImage; procedure Button2Click(Sender: TObject); private { Private declarations } FHandel : THandle; //DLLLLacid: Info Pointer; //為動態載入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.
如有疑問請留言或到本站社區交流討論,感謝閱讀,希望能幫助大家,謝謝大家對本站的支持!