Adding ActiveX Control OCX to WPF

«  Using Aliases in references
Teacher’s Passion »

Adding ActiveX Control OCX to WPF

Since OCX does not follow the WPF rules in design, OCX cannot be added to WPF projects directly. To add the OCX we need to follow these two steps:

  1. Create ActiveX wrapper from OCX using Windows Forms Control Library project.
  2. Create a System.Windows.Forms.Integration.WindowsFormsHost object to host the OCX as a child and then add the host as a child to a container.

Let’s go over these steps.

Create ActiveX wrapper from OCX using Windows Forms Control Library project

This project is only a wrapper to create ActiveX from OCX. Here are the steps:

  • Create a Windows Forms Control Library project

  • Add a reference to OCX in COM category
  • Add OCX to Toolbox – right click on Toolbox and select Choose Items. Then choose COM components and select the OCX. At this point the OCX control should be in your Toolbox
  • Drag the OCX from the Toolbox to your control
  • Set the OCX control’s Dock to fill
  • Build the project
  • The AxInterop.<OCX>Lib.dll is in the bin directory – this dll is going to be added to your WPF project

WPF Project

In the WPF project that will use the OCX follow these steps:

  • Add a reference to WindowsFormsIntegration from .NET category
  • Add a reference to System.Windows.Forms from .NET category
  • Add a reference to AxInterop.<OCX>Lib.dll that was made from last step
  • Add a content container to be used for the OCX control
  • In the WPF window’s Load event handler, add the code for the container
    • First create the host control
    • Create the ActiveX control

  •  Add the ActiveX control as a child to the host
  • Add the host as a child to the container. In this example I used Grid as my container
  • Then call the ActiveX’s functions

After these steps the ActiveX control has been added to your WPF project.

其实主要就是说ocx不能直接添加引用,而是要自己建立一个winform user control library 工程(最好在同一个解决方案中建立),然后生成dll。然后再在我们需要的主工程里面添加dll 的引用进来,再通过windowsFormHost 在页面上或者在代码中添加进来(代码添加如上,页面添加和上一篇一样)

你可能感兴趣的:(Adding ActiveX Control OCX to WPF)