首页 > 代码库 > 在delphi中,DLL加载时做初始化的Demo

在delphi中,DLL加载时做初始化的Demo

library DLLEntry;//dll源码    uses    SysUtils,    Classes,    Dialogs,    Windows;    {$R *.res}    procedure DLLEntryPoint(dwReason : DWord);  begin    case dwReason of      DLL_PROCESS_ATTACH : showMessage(‘映射到进程地址空间‘);      DLL_PROCESS_DETACH : showMessage(‘从进程的地址空间分离出来‘);      DLL_THREAD_ATTACH :  showMessage(‘创建了一个新线程‘);      DLL_THREAD_DETACH : showMessage(‘一个线程正在退出‘);    end;  end;    begin    {首先,把一个过程的指针赋给DLLProc变量}    DLLProc := @DLLEntryPoint;    {调用这个过程}    DLLEntryPoint(DLL_PROCESS_ATTACH);  end.  [delphi] view plaincopyunit mainfrm;//exe源码    interface    uses    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,    Dialogs, StdCtrls, Buttons;    type    //定义一个测试线程    TTestThread = class(TThread)      procedure Execute; override;    end;    TMainForm = class(TForm)      btnLoadLib: TBitBtn;      btnFreeLib: TBitBtn;      BtnCreateThread: TBitBtn;      BtnFreeThread: TBitBtn;      lblCount: TLabel;      procedure btnLoadLibClick(Sender: TObject);      procedure btnFreeLibClick(Sender: TObject);      procedure BtnCreateThreadClick(Sender: TObject);      procedure BtnFreeThreadClick(Sender: TObject);      procedure FormCreate(Sender: TObject);    private      LibHandle: THandle;      TestThread: TTestThread;      Counter: integer;      GoThread: Boolean;      { Private declarations }    public      { Public declarations }    end;    var    MainForm: TMainForm;    implementation    {$R *.dfm}    //线程执行过程  procedure TTestThread.Execute;  begin    while MainForm.GoThread do    begin      MainForm.lblCount.Caption := IntTostr(MainForm.Counter);      Inc(MainForm.Counter);    end;  end;    procedure TMainForm.FormCreate(Sender: TObject);  begin    LibHandle := 0;    TestThread := nil;  end;      //这个过程用于调入动态链接库DLLEntry.dll  procedure TMainForm.btnLoadLibClick(Sender: TObject);  begin    if LibHandle = 0 then    begin      LibHandle := LoadLibrary(‘DLLEntry.dll‘);      if LibHandle = 0 then        raise Exception.Create(‘Unable to Load DLL‘);    end    else      MessageDlg(‘Library already Loaded‘, mtWarning, [mbok], 0);  end;    //这个过程用于释放链接库  procedure TMainForm.btnFreeLibClick(Sender: TObject);  begin    if not (LibHandle = 0) then    begin      FreeLibrary(LibHandle);      LibHandle := 0;    end;  end;    //创建一个线程  procedure TMainForm.BtnCreateThreadClick(Sender: TObject);  begin    if TestThread = nil then    begin      GoThread := True;      TestThread := TTestThread.Create(false);    end;  end;    //释放一个线程  procedure TMainForm.BtnFreeThreadClick(Sender: TObject);  begin    if not (TestThread = nil) then    begin      GoThread := False;      TestThread.Free;      TestThread := nil;      Counter := 0;    end;  end;  end.  

  

在delphi中,DLL加载时做初始化的Demo