本教程介绍如何在C#编程环境下利用AForge库调用和控制计算机上的摄像头设备,适用于希望进行图像处理或视频分析的开发者。
```csharp
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;
using AForge.Video.DirectShow;
using AForge.Video;
namespace AForgeDemo
{
public partial class Form1 : Form
{
private bool DeviceExist = false; // 设备是否存在标志
private FilterInfoCollection videoDevices; // 视频设备列表
private VideoCaptureDevice videoSource = null; // 视频捕获源
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
getCamList(); // 获取摄像头列表
}
private void getCamList()
{
try
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); // 初始化视频设备集合
cbDev.Items.Clear();
if (videoDevices.Count == 0) throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
cbDev.Items.Add(device.Name);
cbDev.SelectedIndex = 0;
}
catch(ApplicationException)
{
DeviceExist = false; // 设备不存在
cbDev.Items.Add(无设备);
}
}
private void CloseVideoSource()
{
if (videoSource != null && videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap img = (Bitmap)eventArgs.Frame.Clone(); // 捕获视频帧
picVideo.Image = img;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CloseVideoSource();
}
private void btnOpen_Click(object sender, EventArgs e)
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[cbDev.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame); // 添加新帧事件处理
CloseVideoSource();
videoSource.DesiredFrameSize = new Size(picVideo.Width, picVideo.Height);
videoSource.Start();
lbinfo.Text = 设备运行...;
}
else {
lbinfo.Text = 没有选择设备;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (videoSource.IsRunning) // 如果视频源正在运行
{
CloseVideoSource();
lbinfo.Text = 设备停止;
}
}
}
}
```