1. 程式人生 > >用程式碼實現註冊Ocx和Dll

用程式碼實現註冊Ocx和Dll

在windows系統中,可以通過Regsvr32來實現註冊ocx或者dl,

程式設計時,呼叫Regsvr32來註冊,卻不能正常執行。尤其是在Win7系統中,需要管理員身份才能執行。

使用下面的程式碼則能正常註冊。

//註冊

function RegisterDllServer(FileName: string): boolean;
var
  nDllAddr: integer;
  bstr: string;
  ProcAddr: Pointer;
  str: PAnsiChar;
begin
  Result := False;

  if not FileExists(FileName) then
    exit;
   
  nDllAddr:=LoadLibrary(PWideChar(FileName));

  if nDllAddr <> 0 then
  begin
    bstr:='DllRegisterServer'+chr(0);
   
    str := PAnsiChar(AnsiString(bstr));
    ProcAddr := GetProcAddress(nDllAddr,str);
    if ProcAddr<>nil then
    begin
      CallWindowProc(ProcAddr,nDllAddr,0,0,0);
      Result := True;
    end;

    FreeLibrary(nDllAddr); 
  end;                    
end;

//反註冊

function UnRegisterDllServer(FileName: string): boolean;
var
  nDllAddr: integer;
  bstr: string;
  ProcAddr: Pointer;
  str: PAnsiChar;
begin
  Result := False;
 
  if not FileExists(FileName) then
    exit;
   
  nDllAddr:=LoadLibrary(PWideChar(FileName));

  if nDllAddr <> 0 then
  begin
    bstr:='DllUnregisterServer'+chr(0);
   
    str := PAnsiChar(AnsiString(bstr));
    ProcAddr := GetProcAddress(nDllAddr,str);
    if ProcAddr<>nil then
    begin
      CallWindowProc(ProcAddr,nDllAddr,0,0,0);
      Result := True;
    end;

    FreeLibrary(nDllAddr); 
  end;                    
end;