15.9 Use an ActiveX Control in a .NET Client


Problem

You need to place an ActiveX control on a window in a .NET Framework application.

Solution

Use an RCW exactly as you would with an ordinary COM component. To work with the ActiveX control at design time, add it to the Visual Studio .NET Toolbox.

Discussion

The .NET Framework includes the same support for all COM components , including ActiveX controls. The key difference is that the RCW class for an ActiveX control derives from the special .NET type System.Windows.Forms.AxHost . Technically, you add the AxHost control to your form, and it communicates with the ActiveX control "behind the scenes." Because AxHost derives from System.Windows.Forms.Control , it provides the standard .NET control properties, methods , and events, such as Location , Size , Anchor , and so on. In the case of an auto-generated RCW, the AxHost classes will always begin with the letters Ax .

You can create an RCW for an ActiveX control as you would for any other COM component, by using Tlbimp.exe or the Add Reference feature in Visual Studio .NET, and then creating the control programmatically. However, an easier approach in Visual Studio .NET is to add the ActiveX control to the Toolbox. (See recipe 11.4 for details.)

Nothing happens to your project when you add an ActiveX control to the Toolbox. However, you can use the toolbox icon to add an instance of the control to your form. The first time you do this, Visual Studio .NET will create the interop assembly and add it to your project. For example, if you add the Microsoft Masked Edit control, which has no direct .NET equivalent, Visual Studio .NET creates an RCW assembly with a name such as AxInterop.MSMask.dll. Here's the code you might expect to see in the hidden designer region that creates the control instance and adds it to the form:

 this.axMaskEdBox1 = new AxMSMask.AxMaskEdBox(); ((System.ComponentModel.ISupportInitialize)(this.axMaskEdBox1)).BeginInit(); //  // axMaskEdBox1 //  this.axMaskEdBox1.Location = new System.Drawing.Point(16, 12); this.axMaskEdBox1.Name = "axMaskEdBox1"; this.axMaskEdBox1.OcxState = ((System.Windows.Forms.AxHost.State)   (resources.GetObject("axMaskEdBox1.OcxState"))); this.axMaskEdBox1.Size = new System.Drawing.Size(112, 20); this.axMaskEdBox1.TabIndex = 0; this.Controls.Add(this.axMaskEdBox1); 

Notice that the custom properties for the ActiveX control are not applied directly through property set statements. Instead, they are restored as a group when the control sets its persisted OcxState property. However, your code can use the control's properties directly.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net