2007. május 20., vasárnap

How to register an ActiveX library at runtime and create the corresponding ActiveX control


Problem/Question/Abstract:

I want to write a client application which, when it starts, scans a given directory for ActiveX Form OCX's. If found, I want each ActiveForm to be loaded into the interface. This forms a modular plug-in style interface. Can anyone give me some advice on how to (register?) invoke and create an ActiveForm given just an OCX.

Answer:

The steps are:

Runtime registration of the ActiveX library
Runtime creation of the ActiveX control
Invoking methods


1. Registration of the ActiveX library


The code can be found in the source code of the TRegSrv project (Delphi4\demos\activex\tregsrv). The crucial steps are listed below (this is a procedure that I'm using myself. Could be that you will have to look for the units to include).


type
  TRegProc = function: HResult; stdcall;

procedure RegisterActiveXControl(Name: string; Extension: string);
{name is the name of the ActiveX control, Extension is 'ocx' or 'dll'}
var
  LibHandle: THandle;
  FileName: TFileName;
  RegProc: TRegProc;
begin
  {don't mind the path, use your own filename of your own ActiveX control}
  FileName := 'C:\Temp\PAx' + Name + '.' + Extension;
  {this line gets a handle to the ActiveX library}
  LibHandle := LoadLibrary(PChar(FileName));
  {prepares the registration}
  @RegProc := GetProcAddress(LibHandle, 'DllRegisterServer');
  if (not (@RegProc = nil)) then
  begin
    {this line executes the registration procedure, if the file is a correct ActiveX library}
    RegProc;
  end;
  {afterwards, the handle to the file is destroyed}
  FreeLibrary(LibHandle);
end;


2. Runtime creation of the corresponding ActiveX control

You need the following, in a procedure, function or method:


var
  AxControl: OleVariant;
begin
  AxControl := CreateOleObject(AxName);
  {in which AxName is something like 'AxLibraryName.AxControlName' (cf. 'Word.Basic'). You can find this AxName in the ProgID section of the registry}
  Result := AxControl.Execute(a, b); {Execute is a method of the AxControl}
end;

Nincsenek megjegyzések:

Megjegyzés küldése