1、准备工作:dll 源码中有
2、工具箱中右键、选择项、浏览找到AForge.Controls.dll添加进去,既可以使用其中的空间
3、设计器中拖动 videoSourcePlayer控件 做显示预览视频,pictureBox控件做拍照显示(注:不按步骤2添加dll可能在工具箱中找不到该空间)
4、代码
using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test1
{
public partial class Form1 : Form
{
private AForge.Controls.VideoSourcePlayer videoSourcePlayer;
private FilterInfoCollection videoDevices;
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 启动视频预览
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//count = 1;
//枚举所有视频输入设备
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
{
MessageBox.Show("未发现视频设备!");
return;
}
VideoCaptureDevice source = new VideoCaptureDevice(this.videoDevices[0].MonikerString);
this.videoSourcePlayer1.SignalToStop();
this.videoSourcePlayer1.WaitForStop();
this.videoSourcePlayer1.VideoSource = source;
this.videoSourcePlayer1.Start();
}
/// <summary>
/// 拍照
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.BackgroundImage = Image.FromHbitmap(videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap());
}
/// <summary>
/// 停止预览
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
this.videoSourcePlayer1.Stop();
GC.Collect();
}
}
}