Windows Forms: How to use webcam in C#

This post shows you how to access webcam using AForge in C#.NET Windows Forms Application.

Drag the Label, Combobox, PictureBox and Button from the visual studio toolbox to your winform, then layout your UI as shown below.

c# webcam example

To use webcam in c# you need to declare two variables as the following c# code.

FilterInfoCollection filterInfoCollection;
VideoCaptureDevice videoCaptureDevice;

Next, Add the Form_Load event handler to delect your camera device, then add the device to the combobox control.

private void Form1_Load(object sender, EventArgs e)
    filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
    foreach (FilterInfo Device in filterInfoCollection)
    cboCamera.SelectedIndex = 0;
    videoCaptureDevice = new VideoCaptureDevice();

Add code to handle the Start button click event as shown below.

private void btnStart_Click(object sender, EventArgs e)
    videoCaptureDevice = new VideoCaptureDevice(filterInfoCollection[cboCamera.SelectedIndex].MonikerString);
    videoCaptureDevice.NewFrame += FinalFrame_NewFrame;

You need to add the FinalFrame_NewFrame event to capture image from the camera as the following c# code.

private void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
    picCamera.Image = (Bitmap)eventArgs.Frame.Clone();

And don't forget to stop the camera when the form closing.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    if (videoCaptureDevice.IsRunning == true)

To access webcam in c# you need to import the namespaces below.

using AForge.Video;
using AForge.Video.DirectShow;

Press F5 to rebuild and run your application, click the Start button you can see your webcam open and capture image from webcam to the PictureBox control in c# windows application.

Related Posts