使用AForge.Controls.VideoSourcePlayer组件
工具-选择工具箱 浏览选择AForge.Controls.dll 然后就有了VideoSourcePlayer组件
using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
namespace WindowsFormsApplication_Video
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
this.FormClosing += Form2_FormClosing;
videoSourcePlayer1.NewFrame += VideoSourcePlayer1_NewFrame;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
ClosVideoSource();
}
private void VideoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
{
DateTime now = DateTime.Now;
Graphics g = Graphics.FromImage(image);
//绘制当前日期
SolidBrush brush = new SolidBrush(Color.Red);
g.DrawString(now.ToString(), this.Font, brush, new PointF(5, 5));
brush.Dispose();
g.Dispose();
}
private void OpenVideoSource(IVideoSource source)
{
videoSourcePlayer1.VideoSource = source;
videoSourcePlayer1.Start();
}
private void ClosVideoSource()
{
if (videoSourcePlayer1.VideoSource != null)
{
if (videoSourcePlayer1.IsRunning)
{
videoSourcePlayer1.Stop();
}
videoSourcePlayer1.VideoSource = null;
}
}
private void playToolStripMenuItem_Click(object sender, EventArgs e)
{
//自带弹窗选择分辨率
VideoCaptureDeviceForm form = new VideoCaptureDeviceForm();
if (form.ShowDialog(this) == DialogResult.OK)
{
VideoCaptureDevice videoSource = form.VideoDevice;
OpenVideoSource(videoSource);
}
//不弹窗
//ClosVideoSource();
//FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
//if (videoDevices.Count == 0)
//{
// MessageBox.Show("未找到摄像头");
// return;
//}
//FilterInfo info = videoDevices[0];//获取第一个摄像头
//VideoCaptureDevice cameraDevice = new VideoCaptureDevice(info.MonikerString);
//OpenVideoSource(cameraDevice);
}
private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
{
ClosVideoSource();
}
}
}