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:
- Create ActiveX wrapper from OCX using Windows Forms Control Library project.
- 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
- 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 在页面上或者在代码中添加进来(代码添加如上,页面添加和上一篇一样)
本文详细介绍了如何将OCX控件引入WPF项目,包括创建ActiveX包装器、添加引用和整合控件到WPF窗口的步骤。




2323

被折叠的 条评论
为什么被折叠?



