Using ActiveX Controls

Add controls to a Windows form.

  • Instantiate and invoke an ActiveX control.

With their roots in the Visual Basic custom control standard, ActiveX controls have become a major means of delivering encapsulated functionality to Windows applications. The key advance underlying ActiveX controls is that they have a standard set of interfaces through which they communicate with the hosting form. By supporting these interfaces, any application can make use of any ActiveX control, without any knowledge of the internal workings of that control.

This concept has turned out to be so popular that thousands of ActiveX controls are now available commercially. You can find controls to display unusual graphs, controls that implement common Internet protocols, controls that emulate spreadsheets, and many more.

But in the .NET world, an ActiveX control is useless. .NET Framework Windows forms can only contain instances of classes that are derived from the System.Windows.Forms.Control class. ActiveX controls, which are built using previous technologies, do not derive from this class. So how can you possibly use an ActiveX control on a Windows form?

The answer lies in the creation of a wrapper. In programming terms, a wrapper is a layer of software whose job is to translate one set of interfaces into another. The System.Windows.Forms namespace contains a wrapper class, AxHost, whose job is to make ActiveX controls available to Windows forms. To a Windows form, this class appears to be a regular Windows forms control. To an ActiveX control, this class appears to be an ActiveX control container. When the form sends a message to the control, or vice versa, the wrapper class translates the message so that the recipient component can understand it.

The AxHost class needs to be customized to work with a particular ActiveX control. That customization is the job of the Windows Forms ActiveX Control Importer, a utility that ships with the .NET Framework.

The Windows Forms ActiveX Control Importer Tool (aximp.exe)

To illustrate the Windows Forms ActiveX Control Importer (aximp.exe), Step by Step 9.1 shows you how to use the SysInfo control, which ships as a part of Visual Basic 6, on a Windows form.

STEP BY STEP

9.1 Using the Windows Forms ActiveX Control Importer Tool

1.
Create a new folder on your hard drive to house the imported control.

2.
Launch a .NET command prompt by selecting Start, Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt.

WARNING

Check the Path You might need to modify the command line for the importer if you're running an operating system other than Windows NT or Windows 2000.

3.
Inside the command prompt window, navigate to the folder that you created in step 1.

4.
Enter this command line to run the importer:

aximp c:winntsystem32sysinfo.ocx

The importer lists the names of the files that it creates as part of the import process:

SysInfoLib.dll
AxSysInfoLib.dll

5.
Open a Visual C# .NET Windows application and add a new form to the project. Name the new form StepByStep9_1.cs.

6.
Right-click the References node in Solution Explorer and select Add Reference. Select the COM tab in the Add Reference dialog box. Browse to the folder you created in step 1. Add references to both SysInfoLib.dll and AxSysInfoLib.dll.

7.
Right-click the form and select View Code from the context menu. Expand the Windows Form Designer Generated Code region. Modify the code for the form as follows:

public class StepByStep9_1 : System.Windows.Forms.Form
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components
       = null;
    private AxSysInfoLib.AxSysInfo sysInfo1;
    public StepByStep9_1()
    {
        //
        // Required for Windows Form Designer support
        //
        InitializeComponent();
        //
        // TODO: Add any constructor code after
        // InitializeComponent call
        //
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
        if( disposing )
        {
            if(components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support-
    /// do not modify the contents of
    /// this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        System.Resources.ResourceManager resources =
            new System.Resources.ResourceManager(
            Type.GetType("_316C09.StepByStep9_1"));
        this.sysInfo1 = new AxSysInfoLib.AxSysInfo();
        ((System.ComponentModel.ISupportInitialize)
             this.sysInfo1).BeginInit();
        this.SuspendLayout();
        //
        //SysInfo1
        //
        this.sysInfo1.Enabled = true;
        this.sysInfo1.Name = "sysInfo1";
        this.sysInfo1.OcxState =
        (System.Windows.Forms.AxHost.State)
         resources.GetObject("SysInfo1.OcxState");
        this.sysInfo1.Size = new System.Drawing.Size(
            38, 38);
        this.sysInfo1.TabIndex = 0;
        //
        // StepByStep9_1
        //
        this.AutoScaleBaseSize =
         new System.Drawing.Size(5, 13);
        this.ClientSize =
         new System.Drawing.Size(292, 273);
        this.Controls.AddRange(
        new System.Windows.Forms.Control[]
        {this.sysInfo1});
        this.Name = "StepByStep9_1";
        this.Text = "StepByStep9_1";
        this.Load +=
           new System.EventHandler(
           this.StepByStep9_1_Load);
        ((System.ComponentModel.ISupportInitialize)
            this.sysInfo1).EndInit();
        this.ResumeLayout(false);

    }
    #endregion
    [STAThread]
    static void Main()
    {
        Application.Run(new StepByStep9_1());
    }

    private void StepByStep9_1_Load(object sender,
       System.EventArgs e)
    {
       MessageBox.Show(sysInfo1.OSVersion.ToString());
    }
}

8.
Switch back to the design view of the form. You should see an instance of the SysInfo control, as shown in Figure 9.1.

Figure 9.1. You can use an ActiveX control on a Windows form by creating a wrapper class using Windows Forms ActiveX Control Importer tool.


9.
Set the form as the startup object for the project.

10.
Run the project. You get a message box that displays the major version number of the operating system.


Although the Windows Forms ActiveX Control Importer does the work of building the necessary wrapper classes for you, you still have to do a lot of work to use those classes. Because the importer does not add the control to the toolbox in Visual Studio .NET, you need to write all the code to initialize the code yourself. Getting this code right can be tricky. Fortunately, there's an easier way to bring an ActiveX control into your .NET Windows application project. You'll learn about that technique in the next section.

Importing Controls with the Toolbox

If you're using Visual Studio .NET to build Visual C# .NET applications (and I assume that you are), you don't have to bother with the Windows Forms ActiveX Control Importer. Instead, you can use the toolbox to add any ActiveX control from your system to the .NET environment. As you'll see, this method takes care of most of the work for you.

STEP BY STEP

9.2 Using the Toolbox to Add an ActiveX Control to a Windows Form

1.
Create a new form in your Visual C# .NET application.

2.
Right-click the toolbox and select Customize Toolbox.

3.
Select the COM Components tab in the Customize Toolbox dialog box.

4.
Scroll down the list of components, which should include all the ActiveX controls that are registered on your computer, until you find the control you want to add to your project. Click the check box for the control. Figure 9.2 shows the Microsoft Masked Edit control being selected.

Figure 9.2. You can add an ActiveX control to a Windows form by adding the control to the Visual Studio .NET toolbox.


NOTE

ActiveX Control Properties ActiveX control properties are directly integrated into the Properties window. You can also click the ActiveX-Properties hyperlink at the bottom of the Properties window to open a property sheet for the control.

5.
Click OK to add the control to the toolbox.

6.
The new control shows up at the bottom of the toolbox, as shown in Figure 9.3. You can click and drag the control to a form just like any native .NET control. Place an instance of the Masked Edit control on your form. Set the Mask property of the Masked Edit control to ##/##/##.

Figure 9.3. An ActiveX control can appear in the Visual Studio .NET toolbox just like any other .NET control.


7.
Insert the Main() method to launch the form. Set the form as the startup object for the project.

8.
Run the project. The form accepts only the numeric characters allowed by the Masked Edit control.


Using ActiveX Controls on Windows Forms

As you've probably guessed by now, using ActiveX controls on Windows forms is easy. Just import the ActiveX control to the .NET Framework (either by running the Windows Forms ActiveX Control Importer or by adding the control to the toolbox), and you can treat it as if it were a native .NET control. But there are a few things you should consider before you use ActiveX controls in your .NET applications.

First and foremost, you should recognize that there's an inevitable performance decrease when you use ActiveX controls on a .NET form. Although the wrapper architecture allows you to seamlessly use an ActiveX control, it imposes a performance penalty. That's because every call to the control is actually a call to the wrapper class, which then must call the control itself after suitably transforming the parameters of the call. Thus your code has to do twice as much work to interact with an ActiveX control as with a native .NET control. If you're using only a few ActiveX controls in a limited number of forms, this performance decrease might not be noticeable, but if you overuse ActiveX controls, it adds up.

When you import some ActiveX controls to the .NET Framework, their names may change to avoid conflicts with existing objects. You're most likely to see this happen if a control has a property named State; such a property is named CtlState after the import.

The code that runs under the services provided by the Common Language Runtime (CLR) is called managed code. Because ActiveX controls are not managed code, they don't get any of the protection that the CLR brings to .NET applications. An ActiveX control is free to access memory that doesn't belong to it or indulge in other buggy behavior that could crash your entire application.

Finally, using ActiveX controls makes it more difficult to deploy .NET applications. In addition to installing the .NET Framework and your own application, you need to make sure that the target machine has a copy of the ActiveX control properly installed and registered.

Because of these drawbacks, you should use ActiveX controls sparingly (if at all). Before importing an ActiveX control into a project, you should consider whether a native .NET control can fill your requirements.

REVIEW BREAK

  • You can use the Windows Forms ActiveX Control Importer to create wrapper classes. These wrapper classes let you host the ActiveX control on a .NET Windows form.

  • You can import an ActiveX control to a Visual Studio .NET project by adding it to the toolbox.

  • After you import ActiveX controls, you can use them just like native .NET controls.

  • ActiveX controls impose a performance penalty and have other drawbacks.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.156