You can use the AForge.NET library to detect and use cameras in C#. Here’s an example code snippet that demonstrates how to detect cameras and capture frames from them:
using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
public class CameraCapture
{
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource;
public CameraCapture()
{
// Get available video devices
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
{
Console.WriteLine("No video devices found.");
return;
}
// Create instance of VideoCaptureDevice using the first available device
videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
// Set NewFrame event handler to capture frames
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
}
public void StartCapture()
{
// Start capturing
videoSource.Start();
}
public void StopCapture()
{
// Stop capturing
videoSource.Stop();
}
private void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
// Process each captured frame here
Bitmap frame = (Bitmap)eventArgs.Frame;
// Display the frame (you can modify this according to your requirements)
PictureBox pictureBox = new PictureBox();
pictureBox.Image = frame;
pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox.Refresh();
}
}
public class Program
{
static void Main(string[] args)
{
CameraCapture cameraCapture = new CameraCapture();
if (cameraCapture.videoDevices.Count > 0)
{
// Start capturing from the first available camera
cameraCapture.StartCapture();
Console.WriteLine("Press Enter to stop capturing...");
Console.ReadLine();
// Stop capturing
cameraCapture.StopCapture();
}
else
{
Console.WriteLine("No camera found.");
}
}
}
Make sure you have the AForge.Video and AForge.Video.DirectShow libraries installed in your project. You can add them through NuGet package manager or by manually referencing them.
This code initializes a CameraCapture
object, which automatically selects the first available camera. It starts capturing frames and displays them in a PictureBox
control. You can modify the videoSource_NewFrame
method to process the captured frames according to your requirements.
Remember to handle exceptions and release resources properly when using camera devices in your application.