Difference between revisions of "LazActiveX/es"

From Lazarus wiki
Jump to navigationJump to search
Line 1: Line 1:
 
{{LazActiveX}}
 
{{LazActiveX}}
 
== Resumen ==
 
== Resumen ==
   El paquete LazActiveX contiene el componente TActiveXContainer y la integración con el IDE de las herramientas necesarias para crear componentes ActiveX desde una biblioteca de tipos o directamente desde el objeto (exe o dll). ActiveX es una tecnología de Microsoft Windows y sólo se puede utilizar en esa plataforma. Compilación cruzada para Windows es posible, pero el importador de biblioteca de tipos (typelib) para crear los enlaces COM sólo funciona en Windows (no probado en Wine)
+
   El paquete LazActiveX contiene el componente TActiveXContainer y la integración con el IDE de las herramientas necesarias para crear componentes ActiveX desde una librería de tipos o directamente desde el objeto (exe o dll). ActiveX es una tecnología de Microsoft Windows y sólo se puede utilizar en esa plataforma. Compilación cruzada para Windows es posible, pero el importador de librerías de tipos (typelib) para crear los enlaces COM sólo funciona en Windows (no probado en Wine)
  
 
== Instalación ==
 
== Instalación ==
  
   '''Aviso''': LazActiveX necesita FPC >= 2.6.1. La importación de bibliotecas de tipos sólo funciona en Windows XP o posterior.
+
   '''Aviso''': LazActiveX necesita FPC >= 2.6.1. La importación de librerías de tipos sólo funciona en Windows XP o posterior.
  
 
   Desde la opción del menú 'Paquete'/'Instalar/Desinstalar Paquetes ...' en la ventana, seleccionar LazActiveX 0.1, y dar al botón 'Instalar Seleccionado' y  después a 'Guardar y Reconstruir el IDE'. Alternativamente, abrir el paquete LazActiveX.lpk  y pulsar en 'Usar >>'/'Instalar'.
 
   Desde la opción del menú 'Paquete'/'Instalar/Desinstalar Paquetes ...' en la ventana, seleccionar LazActiveX 0.1, y dar al botón 'Instalar Seleccionado' y  después a 'Guardar y Reconstruir el IDE'. Alternativamente, abrir el paquete LazActiveX.lpk  y pulsar en 'Usar >>'/'Instalar'.
Line 18: Line 18:
  
 
# Poner el componente TActiveXContainer en un formulario y asignar el nombre de la clase ActiveX a la propiedad OleClassName. Adecuado para el enlace en tiempo de ejecución ( o tardío) y sin el apoyo directo para eventos.
 
# Poner el componente TActiveXContainer en un formulario y asignar el nombre de la clase ActiveX a la propiedad OleClassName. Adecuado para el enlace en tiempo de ejecución ( o tardío) y sin el apoyo directo para eventos.
# Importar la biblioteca de tipo ActiveX, poner el componente TActiveXContainer en un formulario, crear una instancia del objeto ActiveX y asignarlo a la propiedad ComServer. Adecuado para el enlace en tiempo de compilación (o anticipado) y con el apoyo para eventos.
+
# Importar la biblioteca de tipo ActiveX, poner el componente TActiveXContainer en un formulario, crear una instancia del objeto ActiveX y asignarlo a la propiedad ComServer. Adecuado para el enlace en tiempo de compilación (o temprano) y con el apoyo para eventos.
# Crear un nuevo componente desde la biblioteca de tipos o el objeto y poner nuevo componente en el formulario. Esto también utiliza enlace anticipado y tiene soporte completo para eventos. Los controladores de eventos pueden ser asignados desde el IDE.
+
# Crear un nuevo componente desde la librería de tipos o el objeto y poner nuevo componente en el formulario. Esto también utiliza enlace anticipado y tiene soporte completo para eventos. Los controladores de eventos pueden ser asignados desde el IDE.
  
 
=== Enlace tardío de TActiveXContainer===
 
=== Enlace tardío de TActiveXContainer===
Line 31: Line 31:
 
*Colocar un TActiveXContainer, un TButton y un TFileNameEdit en un formulario.
 
*Colocar un TActiveXContainer, un TButton y un TFileNameEdit en un formulario.
  
*Da el tamaño y la posición deseada al componente TActiveXContainer y escribe 'VideoLAN.VLCPlugin.2' en la propiedad OleClassName, pon a verdadera la propiedad Active. Esto dará un formulario similar al siguiente:
+
*Da el tamaño y la posición deseada al componente TActiveXContainer y escribe 'VideoLAN.VLCPlugin.2' en la propiedad OleClassName, pon a verdadera la propiedad Active. Esto dará un formulario similar a este:
  
 
[[Image:LazActiveX-VLC-Form.png]]
 
[[Image:LazActiveX-VLC-Form.png]]
Line 46: Line 46:
 
  end;</syntaxhighlight>
 
  end;</syntaxhighlight>
  
*Ejecuta el programa, selecciona una película y haz clic en el botón para verla. Ten en cuenta que VLC juntocon gdb parecen causar algunos problemas (lenta puesta en marcha en el mejor de los casos, se cuelga o se bloquea). Mejor ejecuta el programa fuera del IDE.
+
*Ejecuta el programa, selecciona una película y haz clic en el botón para verla. Ten en cuenta que VLC junto con gdb parecen causar algunos problemas (lenta puesta en marcha en el mejor de los casos, se cuelga o se bloquea). Mejor ejecuta el programa fuera del IDE.
  
=== TActiveXContainer early binding ===
+
=== Enlace temprano de TActiveXContainer ===
  
Early binding means that all interfaces are known to the compiler. So we need to create the pascal bindings for the ActiveX object. The importtl.exe tool in the fpc utils directory does that for you and creates coclasses and event listeners to facilitate the use of the objects in pascal. A GUI for the importtl.exe tool is integrated with the LazActiveX package and is accessible in the Tools menu: Import Type Library.
+
&nbsp;&nbsp;&nbsp;El Enlace temprano permite conocer todos los interfaces al compilador. Así que tenemos que crear los enlaces pascal para el objeto ActiveX. La herramienta '''importtl.exe''' en el directorio utils FPC lo hace por ti y crea '''''coclases''''' y detectores de eventos para facilitar el uso de los objetos en pascal. Una interfaz gráfica de usuario para la herramienta importtl.exe está integrada con el paquete LazActiveX y es accesible en el menú Herramientas: Import Type Library
  
 
[[Image:LazActiveX-Importtl.png]]
 
[[Image:LazActiveX-Importtl.png]]
  
Check 'Convert dependent typelibs' to convert also the typelibs for the COM objects that are eventually used by the selected object. Clicking OK will start the typelib import and create new units in the IDE. The units have the following naming: LibraryName_MajorVersion_MinorVersion_TLB. Ex: Access_9_0_TLB.  
+
&nbsp;&nbsp;&nbsp;Marca 'Convert dependent typelibs' para convertir también las librerías de tipos para los objetos COM que son finalmente utilizados por el objeto seleccionado. Al hacer clic en Aceptar, se comenzará la importación de librería de tipos y creará nuevas unidades en el IDE. Las unidades tienen la siguiente nomenclatura: NombreLibreriaVersionMayor_VersionMenor_TLB. Ej: Access_9_0_TLB.  
  
: '''Delphi users''': Delphi unit naming does not use version numbers.  
+
: '''Usuarios Delphi''': Los nombres de unidad en Delphi no utilizan los números de versión.  
  
Instantiating an ActiveX object is done at run-time by calling the Create method for the appropriate CoClass created for the library. Some ActiveX libraries expose several objects and multiple CoClasses are created. Consult the documentation for the ActiveX library in case of doubt. Assigning the instantiated ActiveX object to the ComServer property of an TActiveXContainer on a form and setting it's active property to true is all that is needed to embed it in the application.
+
&nbsp;&nbsp;&nbsp;La creación de instancias de un objeto ActiveX se realiza en tiempo de ejecución mediante una llamada al método Create para la CoClass apropiado creado para la librería. Algunas librerías ActiveX exponen varios objetos y por tanto  se crean múltiples coclases. Consulta la documentación de la librería ActiveX en caso de duda. Asignar el objeto instanciado ActiveX a la propiedad de un ComServer TActiveXContainer en un formulario y establecer la propiedad Active en True es todo lo que se necesita para embeberlo en la aplicación
  
'''Example:''' Embed VLC player in a form. VLC has to be installed !!
+
&nbsp;&nbsp;&nbsp;'''Ejemplo:''' Embeber el reproductor VLC en un formulario. ¡VLC ha de estar correctamente instalado!
 
 
- Drop a TActiveXContainer, a TButton and a TFileNameEdit on a form. Resize and position TActiveXContainer to your liking
 
 
 
- Open 'Import Type Library' from the tools menu and select 'axvlc.dll' in your VLC installation directory. Click OK. The AXVLC_1_0_TLB unit is created.
 
 
 
- Add AXVLC_1_0_TLB to the uses clause.
 
  
- Create an OnClick event for the button and an OnCreate event for the form. Enter the following code:
+
*Pon un TActiveXContainer, un TButton y un TFileNameEdit en un formulario. Da el tamaño y la posición deseada al componente TActiveXContainer.
 +
*Abre 'Import Type Library' desde el menú de herramientas y selecciona 'axvlc.dll' en el directorio de instalación de VLC. Clic OK. Se creará la unidad AXVLC_1_0_TLB.
  
<syntaxhighlight>var
+
*Añade AXVLC_1_0_TLB a la cláusula uses.
  VLC:IVLCControl2;
 
  
procedure TForm1.Button1Click(Sender: TObject);
+
*Crea un evento OnClick para el botón y un evento OnCreate para el formulario. Escribe el siguiente código:
begin
 
  VLC.playlist.add(utf8decode(FileNameEdit1.FileName),'',vararrayof([':aspect-ratio=16:9']));
 
  VLC.playlist.play;
 
end;
 
  
procedure TForm1.FormCreate(Sender: TObject);
+
<syntaxhighlight> var
begin
+
  VLC:IVLCControl2;
  VLC:=CoVLCPlugin2.Create;
 
  ActiveXContainer1.ComServer:=VLC;
 
  ActiveXContainer1.Active:=true;
 
end;
 
</syntaxhighlight>
 
- Run the program, select a movie and click the button to view the movie.
 
  
 +
procedure TForm1.Button1Click(Sender: TObject);
 +
  begin
 +
    VLC.playlist.add(utf8decode(FileNameEdit1.FileName),'',vararrayof([':aspect-ratio=16:9']));
 +
    VLC.playlist.play;
 +
  end;
  
 +
procedure TForm1.FormCreate(Sender: TObject);
 +
  begin
 +
    VLC:=CoVLCPlugin2.Create;
 +
    ActiveXContainer1.ComServer:=VLC;
 +
    ActiveXContainer1.Active:=true;
 +
  end;</syntaxhighlight>
  
The typelib importer adds also event support for ActiveX that generate them. In that case, alongside the CoClass a TEventSink descendant is defined that implements the ActiveX object and all its OnEvent properties. Use the TEventSink descendant instead of the CoClass if you want to use the events. Its name starts with TEvs followed by the class name.  
+
*Ejecuta el programa, selecciona una película y pulsa el botón para verla.  
  
'''Example:''' Internet Explorer in a form with event support.
+
&nbsp;&nbsp;&nbsp;El importador de tipos de librerías también añade soporte para los eventos que el ActiveX genera. En este caso, junto a la CoClass se define un descendiente de TEventSink para implementar el objeto ActiveX y todas sus propiedades OnEvent. Utiliza el descendiente de TEventSink en lugar de la CoClass si deseas utilizar los eventos. Su nombre empieza con TEvs seguido por el nombre de la clase.  
  
- Drop a TActiveXContainer, a TButton, TLabel and a TEdit on a form. Resize and position TActiveXContainer to your liking
+
'''Ejamplo:''' Internet Explorer en un formulario con soporte de eventos.
  
- Open 'Import Type Library' from the tools menu and select 'C:\WINDOWS\system32\ieframe.dll'. Click OK. The SHDocVw_1_1_TLB unit is created.
+
*Pon un a TActiveXContainer, un TButton, un TLabel y un TEdit en un formulario. Da el tamaño y la posición deseada al componente TActiveXContainer.
 +
*Abre 'Import Type Library' desde le menú Herramientas y selecciona 'C:\WINDOWS\system32\ieframe.dll'. Pulsa OK. Se creará la unidad SHDocVw_1_1_TLB.
 +
*Añade la unidad SHDocVw_1_1_TLB a la cláusula uses.
 +
*Crea un evento OnClick para el botón y un evento OnCreate para el formulario.  
 +
*Crea en la clase TForm1 el procedimiento privado OnStatusTextChange(Sender: TObject;Text_:WideString);
 +
*Escribe este código:
  
- Add SHDocVw_1_1_TLB to the uses clause.
+
<syntaxhighlight> var
 
 
- Create an OnClick event for the button and an OnCreate event for the form.
 
 
 
- Create in class TForm1 the private procedure OnStatusTextChange(Sender: TObject;Text_:WideString);
 
 
 
- Enter the following code:
 
 
 
<syntaxhighlight>var
 
 
   Browser:TEvsWebBrowser;
 
   Browser:TEvsWebBrowser;
  
procedure TForm1.Button1Click(Sender: TObject);
+
procedure TForm1.Button1Click(Sender: TObject);
var
+
  var
  url,onull:Olevariant;
+
  url,onull:Olevariant;
  
begin
+
  begin
  url:=Utf8decode(Edit1.Text);
+
    url:=Utf8decode(Edit1.Text);
  onull:=NULL;
+
    onull:=NULL;
  Browser.ComServer.Navigate2(url,onull,onull,onull,onull);
+
    Browser.ComServer.Navigate2(url,onull,onull,onull,onull);
end;
+
  end;
  
procedure TForm1.FormCreate(Sender: TObject);
+
procedure TForm1.FormCreate(Sender: TObject);
begin
+
  begin
  Browser:=TEvsWebBrowser.Create(Self);
+
    Browser:=TEvsWebBrowser.Create(Self);
  ActiveXContainer1.ComServer:=Browser.ComServer;
+
    ActiveXContainer1.ComServer:=Browser.ComServer;
  ActiveXContainer1.Active:=true;
+
    ActiveXContainer1.Active:=true;
  Browser.OnStatusTextChange:=@OnStatusTextChange;
+
    Browser.OnStatusTextChange:=@OnStatusTextChange;
end;
+
  end;
  
procedure TForm1.FormDestroy(Sender: TObject);
+
procedure TForm1.FormDestroy(Sender: TObject);
begin
+
  begin
  Browser.Free;
+
    Browser.Free;
end;  
+
  end;  
  
procedure TForm1.OnStatusTextChange(Sender: TObject; Text_: WideString);
+
procedure TForm1.OnStatusTextChange(Sender: TObject; Text_: WideString);
begin
+
  begin
  Label1.Caption:=UTF8Encode(Text_);
+
    Label1.Caption:=UTF8Encode(Text_);
end;
+
  end;</syntaxhighlight>
</syntaxhighlight>
 
- Run the program, enter an URL in the Edit control and click the button to navigate to the URL. Label1 will show the status messages sent by the browser.
 
  
- To access the document object (DOM) you have to import also the typelib from C:\WINDOWS\system32\mshtml.tlb and add the created MSHTML_4_0_TLB to the uses clause. To display for example the contents of the <body> tag of the downloaded page, add a TMemo and a second TButton to the form and add the following code:
+
*Ejecuta el programa, introduce una URL en el control de edición y haz clic en el botón para navegar hasta la dirección URL. Label1 mostrará los mensajes de estado enviados por el navegador.
 +
*Para acceder al objeto de documento (DOM), tienes que importar también la biblioteca de tipos de C:\WINDOWS\system32\mshtml.tlb y añadir la unidad MSHTML_4_0_TLB creada a la cláusula uses. Para mostrar por ejemplo el contenido de la etiqueta <body> de la página descargada, agrega un TMemo y un segundo TButton al formulario y agrega el siguiente código
  
<syntaxhighlight>
+
<syntaxhighlight> procedure TForm1.Button2Click(Sender: TObject);
procedure TForm1.Button2Click(Sender: TObject);
+
  var  Doc: IHTMLDocument2; //defined in MSHTML_4_0_TLB
var  Doc: IHTMLDocument2; //defined in MSHTML_4_0_TLB
+
  begin
begin
+
    Doc := Browser.ComServer.Document as IHTMLDocument2;
  Doc := Browser.ComServer.Document as IHTMLDocument2;
+
    Memo1.Lines.Text := utf8encode(Doc.parentWindow.document.Get_body.innerHTML);
  Memo1.Lines.Text := utf8encode(Doc.parentWindow.document.Get_body.innerHTML);
+
  end;</syntaxhighlight>
end;
 
</syntaxhighlight>
 
  
Note that CoClasses are not destroyed. As all COM objects they are reference counted and destroy themselves when the last reference goes out of scope. The TEventSink descendant has to be destroyed.
+
&nbsp;&nbsp;&nbsp;Ten en cuenta que coclases no se destruye. Como todos los objetos COM tiene un contador de referencias y se destruyen cuando la última referencia está fuera de ámbito. El descendiente TEventSink tiene que ser destruido.
  
 
=== Creating visual ActiveX components from type libraries or objects ===
 
=== Creating visual ActiveX components from type libraries or objects ===
Line 160: Line 149:
 
'''Example''': Embed VLC player in a form. VLC has to be installed !!  
 
'''Example''': Embed VLC player in a form. VLC has to be installed !!  
  
- Open 'Import Type Library' from the tools menu and select 'axvlc.dll' in your VLC installation directory. Check 'Create package'. Click OK. Select a directory to store the package. The AXVLC_1_0_TLBP package and all the needed units are created. Install the AXVLC_1_0_TLBP package and rebuild the IDE.
+
*Open 'Import Type Library' from the tools menu and select 'axvlc.dll' in your VLC installation directory. Check 'Create package'. Click OK. Select a directory to store the package. The AXVLC_1_0_TLBP package and all the needed units are created. Install the AXVLC_1_0_TLBP package and rebuild the IDE.
 
+
*Drop a TAxcVLCPlugin2 (from ActiveX component tab), a TButton and a TFileNameEdit on a form.  
- Drop a TAxcVLCPlugin2 (from ActiveX component tab), a TButton and a TFileNameEdit on a form.  
+
*Set TAxcVLCPlugin2.Active to true and resize and position TActiveXContainer to your liking.
 
+
*Create an Onclick event for the button and enter:
- Set TAxcVLCPlugin2.Active to true and resize and position TActiveXContainer to your liking.
 
 
 
- Create an Onclick event for the button and enter:
 
  
<syntaxhighlight>
+
<syntaxhighlight> uses variants;
uses variants;
+
  ...
...
+
  procedure TForm1.Button1Click(Sender: TObject);
procedure TForm1.Button1Click(Sender: TObject);
+
  begin
begin
+
    AxcVLCPlugin2_1.OleServer.playlist.add(widestring(FileNameEdit1.FileName,'',vararrayof([':aspect-ratio=16:9']));
  AxcVLCPlugin2_1.OleServer.playlist.add(widestring(FileNameEdit1.FileName,'',vararrayof([':aspect-ratio=16:9']));
+
    AxcVLCPlugin2_1.OleServer.playlist.play;
  AxcVLCPlugin2_1.OleServer.playlist.play;
+
  end;</syntaxhighlight>
end;
 
</syntaxhighlight>
 
  
- Run the program, select a movie and click the button to view the movie.  
+
*Run the program, select a movie and click the button to view the movie.  
  
 
Event handlers for the components can be created directly from the Object Inspector. (Note the VLC version 1.1.5.0 typelib advertises events but fails to establish a connection point. This appears to be a bug in VLC).
 
Event handlers for the components can be created directly from the Object Inspector. (Note the VLC version 1.1.5.0 typelib advertises events but fails to establish a connection point. This appears to be a bug in VLC).

Revision as of 23:12, 24 November 2012

Windows logo - 2012.svg

This article applies to Windows only.

See also: Multiplatform Programming Guide

English (en) español (es)

Resumen

   El paquete LazActiveX contiene el componente TActiveXContainer y la integración con el IDE de las herramientas necesarias para crear componentes ActiveX desde una librería de tipos o directamente desde el objeto (exe o dll). ActiveX es una tecnología de Microsoft Windows y sólo se puede utilizar en esa plataforma. Compilación cruzada para Windows es posible, pero el importador de librerías de tipos (typelib) para crear los enlaces COM sólo funciona en Windows (no probado en Wine)

Instalación

   Aviso: LazActiveX necesita FPC >= 2.6.1. La importación de librerías de tipos sólo funciona en Windows XP o posterior.

   Desde la opción del menú 'Paquete'/'Instalar/Desinstalar Paquetes ...' en la ventana, seleccionar LazActiveX 0.1, y dar al botón 'Instalar Seleccionado' y después a 'Guardar y Reconstruir el IDE'. Alternativamente, abrir el paquete LazActiveX.lpk y pulsar en 'Usar >>'/'Instalar'.

   Cuando la instalación termine correctamente, una nueva pestaña 'ActiveX' se añade a la paleta de componentes.

LazActiveX-Install1.png

Utilización

   Existen 3 maneras diferentes de utilizar los componentes de ActiveX:

  1. Poner el componente TActiveXContainer en un formulario y asignar el nombre de la clase ActiveX a la propiedad OleClassName. Adecuado para el enlace en tiempo de ejecución ( o tardío) y sin el apoyo directo para eventos.
  2. Importar la biblioteca de tipo ActiveX, poner el componente TActiveXContainer en un formulario, crear una instancia del objeto ActiveX y asignarlo a la propiedad ComServer. Adecuado para el enlace en tiempo de compilación (o temprano) y con el apoyo para eventos.
  3. Crear un nuevo componente desde la librería de tipos o el objeto y poner nuevo componente en el formulario. Esto también utiliza enlace anticipado y tiene soporte completo para eventos. Los controladores de eventos pueden ser asignados desde el IDE.

Enlace tardío de TActiveXContainer

   Aunque la teoría es bastante compleja, el enlace en tiempo de ejecución (o tardío) es la manera más rápida para crear y ejecutar un componente ActiveX.

   Por enlace tardío se refiere el hecho de que la interfaz con el objeto se realiza completamente en tiempo de ejecución. Las referencias a objetos se almacenan como dispinterfaces en variables variant y los métodos y propiedades de los objetos se descubren en tiempo de ejecución. El compilador genera toda la magia de tiempo de ejecución para ti, pero el inconveniente es que el compilador no es capaz de ayudar a encontrar los nombres de los métodos o propiedades en tiempo de diseño. Una buena documentación para el objeto ActiveX es muy importante (el código de ejemplo para VB puede ser fácilmente traducido a pascal). Todos los errores en los nombres de método y sus parámetros serán errores en tiempo de ejecución. El descubrimiento en tiempo de ejecución también agregará sobrecarga al proceso.

   Ejemplo: Embeber el reproductor VLC en un formulario. ¡VLC ha de estar correctamente instalado!

  • Colocar un TActiveXContainer, un TButton y un TFileNameEdit en un formulario.
  • Da el tamaño y la posición deseada al componente TActiveXContainer y escribe 'VideoLAN.VLCPlugin.2' en la propiedad OleClassName, pon a verdadera la propiedad Active. Esto dará un formulario similar a este:

LazActiveX-VLC-Form.png

  • Crea un evento Onclick para el botón con este código:
 procedure TForm1.Boton1Click(Sender: TObject);
 var
   Actx:variant;
 begin
   Actx:=ActiveXContainer1.ComServer;
   Actx.playlist.add(widestring(FileNameEdit1.FileName));
   Actx.playlist.play;
 end;
  • Ejecuta el programa, selecciona una película y haz clic en el botón para verla. Ten en cuenta que VLC junto con gdb parecen causar algunos problemas (lenta puesta en marcha en el mejor de los casos, se cuelga o se bloquea). Mejor ejecuta el programa fuera del IDE.

Enlace temprano de TActiveXContainer

   El Enlace temprano permite conocer todos los interfaces al compilador. Así que tenemos que crear los enlaces pascal para el objeto ActiveX. La herramienta importtl.exe en el directorio utils FPC lo hace por ti y crea coclases y detectores de eventos para facilitar el uso de los objetos en pascal. Una interfaz gráfica de usuario para la herramienta importtl.exe está integrada con el paquete LazActiveX y es accesible en el menú Herramientas: Import Type Library

LazActiveX-Importtl.png

   Marca 'Convert dependent typelibs' para convertir también las librerías de tipos para los objetos COM que son finalmente utilizados por el objeto seleccionado. Al hacer clic en Aceptar, se comenzará la importación de librería de tipos y creará nuevas unidades en el IDE. Las unidades tienen la siguiente nomenclatura: NombreLibreriaVersionMayor_VersionMenor_TLB. Ej: Access_9_0_TLB.

Usuarios Delphi: Los nombres de unidad en Delphi no utilizan los números de versión.

   La creación de instancias de un objeto ActiveX se realiza en tiempo de ejecución mediante una llamada al método Create para la CoClass apropiado creado para la librería. Algunas librerías ActiveX exponen varios objetos y por tanto se crean múltiples coclases. Consulta la documentación de la librería ActiveX en caso de duda. Asignar el objeto instanciado ActiveX a la propiedad de un ComServer TActiveXContainer en un formulario y establecer la propiedad Active en True es todo lo que se necesita para embeberlo en la aplicación

   Ejemplo: Embeber el reproductor VLC en un formulario. ¡VLC ha de estar correctamente instalado!

  • Pon un TActiveXContainer, un TButton y un TFileNameEdit en un formulario. Da el tamaño y la posición deseada al componente TActiveXContainer.
  • Abre 'Import Type Library' desde el menú de herramientas y selecciona 'axvlc.dll' en el directorio de instalación de VLC. Clic OK. Se creará la unidad AXVLC_1_0_TLB.
  • Añade AXVLC_1_0_TLB a la cláusula uses.
  • Crea un evento OnClick para el botón y un evento OnCreate para el formulario. Escribe el siguiente código:
 var
   VLC:IVLCControl2;

 procedure TForm1.Button1Click(Sender: TObject);
  begin
    VLC.playlist.add(utf8decode(FileNameEdit1.FileName),'',vararrayof([':aspect-ratio=16:9']));
    VLC.playlist.play;
  end;

 procedure TForm1.FormCreate(Sender: TObject);
  begin
    VLC:=CoVLCPlugin2.Create;
    ActiveXContainer1.ComServer:=VLC;
    ActiveXContainer1.Active:=true;
  end;
  • Ejecuta el programa, selecciona una película y pulsa el botón para verla.

   El importador de tipos de librerías también añade soporte para los eventos que el ActiveX genera. En este caso, junto a la CoClass se define un descendiente de TEventSink para implementar el objeto ActiveX y todas sus propiedades OnEvent. Utiliza el descendiente de TEventSink en lugar de la CoClass si deseas utilizar los eventos. Su nombre empieza con TEvs seguido por el nombre de la clase.

Ejamplo: Internet Explorer en un formulario con soporte de eventos.

  • Pon un a TActiveXContainer, un TButton, un TLabel y un TEdit en un formulario. Da el tamaño y la posición deseada al componente TActiveXContainer.
  • Abre 'Import Type Library' desde le menú Herramientas y selecciona 'C:\WINDOWS\system32\ieframe.dll'. Pulsa OK. Se creará la unidad SHDocVw_1_1_TLB.
  • Añade la unidad SHDocVw_1_1_TLB a la cláusula uses.
  • Crea un evento OnClick para el botón y un evento OnCreate para el formulario.
  • Crea en la clase TForm1 el procedimiento privado OnStatusTextChange(Sender: TObject;Text_:WideString);
  • Escribe este código:
 var
  Browser:TEvsWebBrowser;

 procedure TForm1.Button1Click(Sender: TObject);
  var
   url,onull:Olevariant;

  begin
    url:=Utf8decode(Edit1.Text);
    onull:=NULL;
    Browser.ComServer.Navigate2(url,onull,onull,onull,onull);
  end;

 procedure TForm1.FormCreate(Sender: TObject);
  begin
    Browser:=TEvsWebBrowser.Create(Self);
    ActiveXContainer1.ComServer:=Browser.ComServer;
    ActiveXContainer1.Active:=true;
    Browser.OnStatusTextChange:=@OnStatusTextChange;
  end;

 procedure TForm1.FormDestroy(Sender: TObject);
  begin
    Browser.Free;
  end; 

 procedure TForm1.OnStatusTextChange(Sender: TObject; Text_: WideString);
  begin
    Label1.Caption:=UTF8Encode(Text_);
  end;
  • Ejecuta el programa, introduce una URL en el control de edición y haz clic en el botón para navegar hasta la dirección URL. Label1 mostrará los mensajes de estado enviados por el navegador.
  • Para acceder al objeto de documento (DOM), tienes que importar también la biblioteca de tipos de C:\WINDOWS\system32\mshtml.tlb y añadir la unidad MSHTML_4_0_TLB creada a la cláusula uses. Para mostrar por ejemplo el contenido de la etiqueta <body> de la página descargada, agrega un TMemo y un segundo TButton al formulario y agrega el siguiente código
 procedure TForm1.Button2Click(Sender: TObject);
  var  Doc: IHTMLDocument2; //defined in MSHTML_4_0_TLB
   begin
     Doc := Browser.ComServer.Document as IHTMLDocument2;
     Memo1.Lines.Text := utf8encode(Doc.parentWindow.document.Get_body.innerHTML);
   end;

   Ten en cuenta que coclases no se destruye. Como todos los objetos COM tiene un contador de referencias y se destruyen cuando la última referencia está fuera de ámbito. El descendiente TEventSink tiene que ser destruido.

Creating visual ActiveX components from type libraries or objects

Instead of using the TActiveXContainer component directly the importtl tool can create TActiveXContainer descendants for every ActiveX object embedded in the type library and create a lpk package for you. The descendants have full support for events generated by the objects. To create a package with the ActiveX components open the 'Import Type Library' window in the 'Tools' menu. Select the library to import, check 'Create package' and eventually 'Convert dependent typelibs', click on 'OK' to create the package. You will be prompted for a directory to store the package. Install the new package. After the Lazarus rebuild you'll find the new components in the ActiveX tab of the component palette.

LazActiveX-Install2.png

Example: Embed VLC player in a form. VLC has to be installed !!

  • Open 'Import Type Library' from the tools menu and select 'axvlc.dll' in your VLC installation directory. Check 'Create package'. Click OK. Select a directory to store the package. The AXVLC_1_0_TLBP package and all the needed units are created. Install the AXVLC_1_0_TLBP package and rebuild the IDE.
  • Drop a TAxcVLCPlugin2 (from ActiveX component tab), a TButton and a TFileNameEdit on a form.
  • Set TAxcVLCPlugin2.Active to true and resize and position TActiveXContainer to your liking.
  • Create an Onclick event for the button and enter:
 uses variants;
   ...
  procedure TForm1.Button1Click(Sender: TObject);
   begin
     AxcVLCPlugin2_1.OleServer.playlist.add(widestring(FileNameEdit1.FileName,'',vararrayof([':aspect-ratio=16:9']));
     AxcVLCPlugin2_1.OleServer.playlist.play;
   end;
  • Run the program, select a movie and click the button to view the movie.

Event handlers for the components can be created directly from the Object Inspector. (Note the VLC version 1.1.5.0 typelib advertises events but fails to establish a connection point. This appears to be a bug in VLC).

Delphi users: Delphi creates a stub for every method and property in its ActiveX components. importtl does not add this additional layer and the AxctiveX methods are called through the components OleServer property. Fe. AxcVLCPlugin2_1.OleServer.playlist.play is the equivalent to VLCPlugin21.playlist.play in Delphi.