场景

效果

C#中实现视频播放器窗体程序(附源码下载)_System

 

实现

新建窗体程序,然后从工具箱中拖拽DataGridView控件,然后在控件右上角点击新增列,设置好每列

的Name属性和Headertext属性。

C#中实现视频播放器窗体程序(附源码下载)_System_02

C#中实现视频播放器窗体程序(附源码下载)_System_03

 

 

新建Video类

项目-右击-新增-类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyPlayer
{
class Video
{
public Video(string id, string name, string path)
{
this.ID = id;
this.Name = name;
this.Path = path;
}

//编号
public string ID { get; set; }

//名称
public string Name { get; set; }

//路径
public string Path { get; set; }
}
}

初始化播放列表

首先声明一个全局的视频列表对象

List<Video> videoList = new List<Video>();

然后在窗体的构造方法中添加初始化播放列表的方法。

其位置

C#中实现视频播放器窗体程序(附源码下载)_List_04

 

在Init方法中

 

public void Init()
{
videoList.Add(new Video("1", "前言", @"F:\全网首个微信小程序开发视频教程\1.0前言.mp4"));
videoList.Add(new Video("2", "课程介绍", @"F:\全网首个微信小程序开发视频教程\1.1课程介绍,定个小目标.mp4"));
videoList.Add(new Video("3", "开发文档", @"F:\全网首个微信小程序开发视频教程\1.2开发文档简读,了解全貌.mp4"));
//设置DataGridView的数据源
UpdateDgv();
}

这里视频采用的是本地绝对路径的视频。

播放列表添加完之后,将视频列表赋值给DataGridView。

public void UpdateDgv()
{
//设置DataGridView的数据源
this.dgvVedioList.DataSource = videoList;
}

其中dgvVedioList就是对应的DataGridView控件的name属性。

新建播放页面

项目-右键-添加-Windows窗体

然后在工具箱中拖拽一个WindowsMediaPlayer组件。

VS2013工具箱中使用WindowsMediaPlyer控件

添加播放组件后

C#中实现视频播放器窗体程序(附源码下载)_ide_05

 

编写其Play方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyPlayer
{
public partial class FrmPlayer : Form
{
//独一无二的实例

private static FrmPlayer uniquePlayer;

//私有构造函数

private FrmPlayer()
{
InitializeComponent();
}
//检查并创建唯一实例
public static FrmPlayer GetInstance()
{
if (uniquePlayer == null)
{
uniquePlayer = new FrmPlayer();
}
return uniquePlayer;
}

//播放节目
public bool Play(string videoPath)
{
try
{
//播放成功后返回true
this.wmp.URL = videoPath;
return true;
}
catch (Exception ex)
{
//播放器异常返回false
MessageBox.Show("播放器异常" + ex.Message);
return false;
}
}

//关闭过程中将实例引用设为null
private void FrmPlayer_FormClosing(object sender, FormClosingEventArgs e)
{
FrmPlayer.uniquePlayer = null;
}

private void wmp_Enter(object sender, EventArgs e)
{

}
}
}

 

配置右键菜单

回到播放列表的页面,拖拽一个ContextMenuStrip组件,设置右键播放菜单。

然后将DataGridView与之关联。具体可参照如下:

C# Winform程序中DataGridView中使用ContextMenuStrip实现右键菜单

配置右键菜单的点击事件

private void tsmiPlayer_Click(object sender, EventArgs e)
{
//获取播放路径
string videoPath = this.dgvVedioList.CurrentRow.Cells["path"].Value.ToString();
if (!File.Exists(videoPath))
{
MessageBox.Show("文件不存在!","提示");
return;
}
//创建单例--视频播放页面窗体
FrmPlayer myPlayer = FrmPlayer.GetInstance();
bool result = myPlayer.Play(videoPath);
if (result)
{
//显示
myPlayer.Show();
}
else
{
//释放
myPlayer.Dispose();
}
}