Hosting an ActiveX Control on a Windows Form

This topic demonstrates how to host the WebBrowser ActiveX control in a form by building an MDI WebBrowser application.

Windows Forms and ActiveX Controls

Windows Forms can only host Windows Forms controls. All Windows Forms controls are classes that are derived from the System.Windows.Forms.Control class. In order for an ActiveX control to be hosted on a form, it must appear like a Windows Forms control. Conversely, an ActiveX control must appear to be hosted in an ActiveX control container. The System.Windows.Forms.AxHost class (which derives from System.Windows.Forms.Control) acts as a Windows Forms control "on the outside" and acts as an ActiveX control container "on the inside." In order to host an ActiveX control, you must create a wrapper class that derives from System.Windows.Forms.AxHost. This control hosts the ActiveX control and exposes its properties, methods, and events (PMEs) as PMEs of the generated conrtrol.


All conversions are done for an entire ActiveX control type library at the same time. You cannot use Aximp.exe to generate type information for a subset of the types defined within a single type library. The output of Aximp.exe is a set of binary files that contain the metadata and control implementation for the types defined within the original type library. The generated files are named according to the following pattern:

  • common language runtime proxy for COM2 types: <PROGID>.dll
  • Windows Forms proxy for ActiveX Controls: Ax<PROGID>.dll

You can examine these files with tools such as Metainfo.exe or Ildasm.exe.

Creating an ActiveX Control Wrapper

You create the the ActiveX control wrapper using the Aximp.exe tool included in the SDK. The following is an example of how to call Aximp.exe.

aximp c:\winnt\system32\shdocvw.dll

Using the Wrapper Control

Once you have created the control wrapper class you can use it in the same way that you would any Windows Forms control. The following example demonstrates how to add a WebBrowser control to a Form.


....
Imports AxSHDocVw
....
AxWebBrowser1.BeginInit()
....
AxWebBrowser1.Location = New System.Drawing.Point(0, 24)
AxWebBrowser1.Size = New System.Drawing.Size(650, 456)
AxWebBrowser1.Dock = System.Windows.Forms.DockStyle.Fill
AxWebBrowser1.TabIndex = 3
....
Me.Controls.Add(AxWebBrowser1)
....
AxWebBrowser1.EndInit()
....
VB

Once you have finished writing the code for your form, you can build it and pass in references to the wrapper DLL files.


vbc.exe /nologo /t:exe /debug+ /R:System.DLL /R:System.Windows.Forms.DLL
/R:System.Drawing.DLL /R:shdocvw.dll /R:AxShDocVw.DLL
/out:MDIBrowser.exe MainForm.vb Document.vb
VB

Web Browser Control Sample

The following sample demonstrates how to host an ActiveX control.

To view and run this sample.

 
VB Browser Sample

[Run Sample] | [View Source]


Copyright 2001 Microsoft Corporation. All rights reserved.