Windows Forms: QR Code scanner using Camera in C#

This post shows you how to read qr code from webcam using AForge , ZXing.Net in C#.NET Windows Forms Application.

To create a QR Code scanner with webcam, you need to drag the TextBox, Label, PictureBox, Combobox and Button from the visual studio toolbox to your winform, then design a simple UI that allows you to read data QR Code using webcam camera as shown below.

c# qr code reader webcam

To play the demo, you need to install the AForge, AForge.Video, AForge.Video.DirectShow, ZXing.Net packages from the Nuget Manage Packages in your visual studio.

Next, Declare two variables as shown below.

FilterInfoCollection filterInfoCollection;
VideoCaptureDevice videoCaptureDevice;

Add code to handle Form_Load event allows you to detect the camera, then you can select the camera you want to use as the following c# code.

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

Add code to handle the Start button click event allows you to show the camera image in the PictureBox control.

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

And don't forget to add the FinalFrame_NewFrame event allows you to capture image from camera.

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

Open the form designer, then drag the timer control from the visual studio toolbox to your winform, then set Interval property to 1000 (1 second). Next, Double click on timer control to add the timer tick event handler as the following c# code.

private void timer1_Tick(object sender, EventArgs e)
{
    BarcodeReader Reader = new BarcodeReader();
    Result result = Reader.Decode((Bitmap)pictureBox1.Image);
    if (result != null)
        txtResult.Text = result.ToString();
}

Finaly, Call the Start method of timer in the Decode button click event handler.

private void btnDecode_Click(object sender, EventArgs e)
{
    timer1.Start();
}

And don't forget to stop webcam when your form closing.

private void Form24_FormClosing(object sender, FormClosingEventArgs e)
{
    if (videoCaptureDevice.IsRunning == true)
        videoCaptureDevice.Stop();
}

You need to import the namespaces below.

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

Run your project, try to find the QR Code sample to test your application.