做下图的Media player播放器。
方法如下:
1、调用Media Player的Com组件。如下图:
2、添加完成后,会在工具箱中出现Windows Media Player控件。如下图:
3、拖入相关控件到窗体中,如第一幅图。并编写代码。相关代码如下:
using System.IO;
namespace MyMedia
{
public partial class FormPlayer : Form
{
public FormPlayer()
{
InitializeComponent();
//选择文件事件
btnFile.Click += new EventHandler(btnFile_Click);
//退出
btnExit.Click += new EventHandler(btnExit_Click);
}
/// <summary>
/// 选择文件事件方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnFile_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog opfPlayer = new OpenFileDialog();
DialogResult drPlayer = opfPlayer.ShowDialog();
if (drPlayer == DialogResult.OK)
{
string sFile = opfPlayer.FileName;
//被播放文件地址(wmpPlayer为被拖入窗体中的播放控件)
wmpPlayer.URL = sFile;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 退出程序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
namespace MyMedia
{
public partial class FormPlayer : Form
{
public FormPlayer()
{
InitializeComponent();
//选择文件事件
btnFile.Click += new EventHandler(btnFile_Click);
//退出
btnExit.Click += new EventHandler(btnExit_Click);
}
/// <summary>
/// 选择文件事件方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnFile_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog opfPlayer = new OpenFileDialog();
DialogResult drPlayer = opfPlayer.ShowDialog();
if (drPlayer == DialogResult.OK)
{
string sFile = opfPlayer.FileName;
//被播放文件地址(wmpPlayer为被拖入窗体中的播放控件)
wmpPlayer.URL = sFile;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 退出程序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
运行程序,选择文件,你的Media Player程序就可以播放音乐啦!