当前位置:文档之家› 如何在WPF中使用ActiveX

如何在WPF中使用ActiveX

如何在WPF中使用ActiveX
如何在WPF中使用ActiveX

如何在WPF中使用ActiveX

原理:ActiveX 需要封装到WinForm 控件中。在WPF中使用WindowsFormsHost 展现。

具体步骤:

一、创建一个名为HostingAxInWpf的WPF 应用程序项目。

二、选择“解决方案”,右单击,“添加”——>“新建项目”,向这个解决方案添加一个Windows 窗体控件库项目,并将其命名为WmpAxLib。

三、选择WmpAxLib项目,右单击,点击“引用”

在弹出的窗口中,点击“添加新引用”

点击“COM”标签,添加对Windows Media Player 程序集(名为wmp.dll)的引用。

四、打开“工具箱”, 在“工具箱”中右击,再单击“选择项”。

击“确定”。这时,Windows Media Player 控件会添加到“工具箱”中。

五、从“工具箱”中,将Windows Media Player 控件添加到设计图面。

在“属性”窗口中,将Windows Media Player 控件的Dock 属性的值设置为Fill。

生成WmpAxLib 控件库项目。这时,在HostingAxInWpf\WmpAxLib\Interop 目录下,会发现2个dll文件:AxXXXLib.dll 和XXXLib.dll (xxx为控件名称)

至此,ActiveX 控件创建完毕。

六、在WPF中使用ActiveX控件

1)在HostingAxInWpf 项目中,引用自定义ActiveX控件:WmpAxLib。方法是:选中HostingAxInWpf的引用文件夹,右单击,“添加引用”。

选择“项目”,添加自定义控件的引用。

2)选择.NET标签,添加一个对名为WindowsFormsIntegration.dll 的

WindowsFormsIntegration 程序集的引用。

添加一个对名为 System.Windows.Forms.dll 的 Windows 窗体程序集的引用。

3)如图,在WPF 设计器中打开Window1.xaml。将Grid元素命名为grid1

xmlns="https://www.doczj.com/doc/4914497716.html,/winfx/2006/xaml/presentation"

xmlns:x="https://www.doczj.com/doc/4914497716.html,/winfx/2006/xaml"

Title="Window1" Height="300" Width="300">

单击“事件”选项卡。

双击Loaded事件,添加如下代码:

private void Window_Loaded(object sender, RoutedEventArgs e)

{

// Create the interop host control.

System.Windows.Forms.Integration.WindowsFormsHost host =

new System.Windows.Forms.Integration.WindowsFormsHost();

// Create the ActiveX control.

AxWMPLib.AxWindowsMediaPlayer axWmp = new AxWMPLib.AxWindowsMediaPlayer();

// Assign the ActiveX control as the host control's child.

host.Child = axWmp;

// Add the interop host control to the Grid

// control's collection of child controls.

this.grid1.Children.Add(host);

// Play a .wav file with the ActiveX control.

axWmp.URL = @"C:\Windows\Media\tada.wav";

}

5)最后,在WPF项目(HostingAxInWpf)中添加对自定义的2个dll的引用:

编译,运行,程序显示如下界面:

wpf自定义slider控件

自定义Slider控件 最终效果: 界面: