WPF 中嵌入Windows Media Player
上一篇通过MediaElement 控件在WPF 4 中制作了简单的媒体播放器。本篇将直接把Windows Media Player 嵌入WPF 中实现同样的效果。起初创建该实例是基于.Net Framework 4.0 完成后编译顺利通过,但F5 时出现了问题。提示无法加载Interop.WMPLib,调试了许久也没搞出个明堂。最后转用.Net 3.5 问题解决,难道是4.0 不支持?感兴趣的朋友可下载代码进一步研究。
创建项目
1. 新建一个基于.Net Framework 3.5 的WPF 应用程序项目:WPFWMP。
2. 在工程中新建Windows Forms Control Library 项目:WMPControlLibrary。
创建WMP 控件
下面要在WMPControlLibrary 中创建Windows Media Player 控件,在项目中加入Windows Media Player COM。
在左侧工具栏中若没有Windows Media Player 控件的话,可以右键General 选择Choose Items,在COM 组件列表中勾选Windows Media Player 选项。
将Windows Media Player 控件拖入设计窗口,并将Dock 设置为Fill 填充控件。
控件效果图:
F6 编译项目后会生成以下三个DLL 文件,这就是我们稍后将要在WPF 中用到的WMP 控件库。
嵌入WMP 控件
回到WPF 项目在前篇文章的基础上,保留其中“Open File” 按键和Button 样式。将上面三个DLL 文件及System.Windows.Forms、WindowsFormsIntegration 加入项目。
在XAML 中加入AxWMPLib 命名空间,并将上篇MediaElement 替换为AxWindowsMediaPlayer 控件,注意此处是将WinForm 控件嵌入WPF 程序,所以要将AxWindowsMediaPlayer 控件放到<WindowsFormsHost>标签中。
<Window x:Class="WPFWMP.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mediaControl="clr-namespace:AxWMPLib;assembly=AxInterop.WMPLib" Title="WPF Media Player" Height="450" Width="520" Background="#FF554D4D"> <Window.Resources> <Style x:Key="btnStyle" TargetType="Button"> … …
</Style> </Window.Resources> <StackPanel HorizontalAlignment="Center" Margin="10"> <Border BorderThickness="3" Background="Black"> … …
<WindowsFormsHost Height="340" Width="450"> <mediaControl:AxWindowsMediaPlayer x:Name="wpfMediaPlayer"/> </WindowsFormsHost> </Border> <Button Content="Open File" Click="openFile_Click" Margin="10" Width="80" Style="{StaticResource btnStyle}"/> </StackPanel> </Window>
通过Windows API Code Pack 为“Open File” 按键添加点击事件,默认打开Sample Video 文件夹,选择视频文件后自动播放。
private void openFile_Click(object sender, RoutedEventArgs e) { ShellContainer selectedFolder = null; selectedFolder = KnownFolders.SampleVideos as ShellContainer; CommonOpenFileDialog cfd = new CommonOpenFileDialog(); cfd.InitialDirectoryShellContainer = selectedFolder; cfd.EnsureReadOnly = true; cfd.Filters.Add(new CommonFileDialogFilter("WMV Files", "*.wmv")); cfd.Filters.Add(new CommonFileDialogFilter("AVI Files", "*.avi")); cfd.Filters.Add(new CommonFileDialogFilter("MP3 Files", "*.mp3")); if (cfd.ShowDialog() == CommonFileDialogResult.OK) { wpfMediaPlayer.URL = cfd.FileName; } }
源代码下载
出处:{GnieTech} (http://www.cnblogs.com/gnielee/)
版权声明:本文的版权归作者与博客园共有。转载时须注明本文的详细链接,否则作者将保留追究其法律责任。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?