How to use barcode scanner in C# Windows Forms Application?

How to scan, read barcode images in WinForms (.NET Core) desktop applications with free C# barcode example source code

Using Free C# Souce Code to read, recognize barcodes in .NET WinForms (Core) Applications & Projects



This C# Windows tutorial provides a step by step guide for building a new Windows Forms application, where user can upload a image with barcode and scan, read the barcode value to textbox.

Windows Forms is a UI framework that creates rich desktop client apps for Microsoft Windows. In this tutorial, you learn how to use Visual Studio .NET to create a new Windows Forms app. With Visual Studio, you add controls to allow users to input barcode image and display the scanned barcode data message in a form.

By the end of this tutorial, you have a simple desktop app

  • Read 20+ barcodes data from images in C# Windows Forms desktop application
  • Support both System.Drawing.Common for Windows
  • Support .NET 9, 8, 7, 6, 5 and .NET Core 3.1, 2.1 Windows application

How to read linear, 2d barcodes in Windows Forms Core desktop app using C#

  1. Download C#.NET Barcode Reader Library
  2. Install C# library to scan barcode images in Windows app
  3. Step by Step Tutorial








What is Barcode Scanner?

Top
A barcode is a scannable image, and it is a visual, machine-readable way to represent numbers and text, such as product information or identifiers A barcode scanner (or barcode reader) is a special device or software application that scans and reads barcodes.

The following contents will demostrate how to build a barcode scanner Windows application using C# Barcode Reader library.

How to read barcode in C# WinForms app?

  • Create a .NET Windows Forms application using Microsoft Visual Studio
  • Install C# Barcode Reader Library
  • Enable barcode scanner function, and support scan, get barcode value in texbox on Windows Form
  • Customize QR Code and Barcode Scanner options
  • Scanning multiple barcode formats
  • Speed up reading performance




Create a new Windows Forms (.NET 5+) application with barcode reader using C#

Top
In the following C# tutorial, we will use C# Barcode Reader library to enable a barcode scanner in a Windows Forms desktop application. With a barcode scanner equipped in a Windows application, barcode images can be scanned from web or Windows connected camera.

Here we will explain step by step how to create a barcode scanner Windows app using C# Barcode Scanner library.
  • Build a new .NET Windows Forms app
  • Install C# Barcode Reader Library
  • Enable barcode scanning function in the Windows application


1. Create new Windows Forms App



Start Visual Studio 2022 and select "Create a new project".

Select "Windows Forms App" in the dialog, and then press "Next" button.





Create a new web project with name "OnBarcodeReaderWinFormsDotNetCoreDemo".





Select .NET 6.0 (Long-term support), and then press "Create"

Now, all auto-generated files for Windows Forms Core barcode reader demo project could be found in the solution explorer.







2. Install Barcode Reader Library dll and NuGet Package



Add OnBarcode Barcode Reader library for WPF Core DLL reference "OnBarcode.Barcode.BarcodeScanner.dll".





Right-click "Dependencies" in the Solution Explorer, and select "Manage NuGet Packages".





Select "Browse" and use the search control to find "System.Drawing.Common" from the package source "nugget.org".





Choose the version 6.0.0 or later to install the package.





Check "Packages" in the Solution Explorer to ensure the installation is success.







3. Design Windows Forms UI



Use Toolbox to add controls to the form "Form1".

Change the property Size of control "Form1" to "720, 480" in the Properties window first.



Step 1: With the "Form1" form designer open, use the Toolbox window to add the following controls to the form by dragging them from the toolbox and dropping them on the form:

  • A Button with a TextBox for choosing a source image file
  • A TextBox for selected barcode image file path
  • A Label with a ComboBox for barcode type
  • A Button for Scan Image
  • A TextBox to get, display barcode value
Position and size the controls according to the following image:


Step 2: change properties of controls for choosing source image file.

You can either move and resize the controls with the mouse to match the final UI below, or use the following controls' property settings to configure each control. To configure a control, select it in the designer, then set the appropriate setting in the Properties window.



Change Button control name to "btChooseFile"; then set properties Text to "Choose File", Location to "25, 35" and Size to "120, 23".



Change TextBox control name to "tbFilePath"; then set properties Location to "155, 36" and Size to "300, 23".



Change property Text of control "label1" to "Barcode Type:" and Location to "470, 39".



Change ComboBox control name to "cbBarcodeType"; then set properties Location to "560, 35".



Change Button control name to "btScanImage"; then set properties Text to "Scan Image", Location to "280, 83" and Size to "150, 23".



Change TextBox control name to "tbScanResult"; then set properties Location to "25, 140" and Size to "656, 270".



Now, the Form1 should be look like below.







4. Add C# code to the Form



Now that the form has all of its controls laid out, the next step is to add event handlers to respond to user input.

Select "View Code" from the menu to open the Form1.cs window.





Replace all contents in the Form1.cs file by following codes.
using System;
using System.Text;
using System.Drawing;
using OnBarcode.Barcode.BarcodeScanner;

namespace OnBarcodeReaderWinFormsDotNetCoreDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //  Initial Controls
            this.tbFilePath.ReadOnly = true;
            this.cbBarcodeType.Items.AddRange(new String[] {
                "AustraliaPost", "Codabar", "Code39", "Code39Extension", "Code93",
                "Code128", "DataMatrix", "EAN8", "EAN13", "Identcode",
                "IntelligentMail", "Interleaved2of5", "ISBN", "ISSN", "ITF14",
                "Leitcode", "PatchCode", "PDF417", "Planet", "Postnet",
                "QRCode", "RM4SCC", "UPCA", "UPCE"
            });
            //  Default Barcode Type: Code 128
            this.cbBarcodeType.SelectedIndex = 5;
            this.btScanImage.Enabled = false;
            this.tbScanResult.ReadOnly = true;
            this.tbScanResult.Multiline = true;
        }

        private void btChooseFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    this.tbFilePath.Text = openFileDialog.FileName;
                    this.btScanImage.Enabled = true;
                }
                catch (Exception) { }
            }
        }

        private void btScanImage_Click(object sender, EventArgs e)
        {
            try
            {
                String filePath = this.tbFilePath.Text;
                if (String.IsNullOrEmpty(filePath))
                    throw new Exception("File path is null or empty.");
                if (!File.Exists(filePath))
                    throw new Exception("File does not exist.");

                //  Get enum BarcodeType from ComboBox selected index.
                BarcodeType barcodeType = (BarcodeType)this.cbBarcodeType.SelectedIndex;

                String[] result = BarcodeScanner.Scan(filePath, barcodeType);

                //  Show scan result in the scan result TextBox.
                StringBuilder sb = new StringBuilder();
                if (result.Length > 0)
                {
                    sb.Append("Number of Barcode: " + result.Length + "\r\n");
                    foreach (String s in result)
                        sb.Append("Message: '" + s + "'\r\n");
                }
                else
                {
                    sb.Append("No Barcode Found.");
                }

                this.tbScanResult.Text = sb.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}




5. Add C# code to all Button events



Select "btChooseFile" Button control in the Form and switch to Event tab in the Properties window, and then add Click event "btChooseFile_Click".



Select "btScanImage" Button control, and then add Click event "btScanImage_Click".





6. It is done. Now press "Ctrl+F5" to run the project.







Scan and customize barcode scanner options using C#

Top


OnBarcode C# Barcode Scanner Library uses ScanOptions object to customize barcode scanner behavier. For example using ScanOptions, you can easily scan GS1 data elements from QR Code, Data Matrix, GS1-128 barcodes.

  • Initialize ScanOptions with Code 128 barcode (GS1-128 is based barcode Code 128)
  • Enable GS1 barcode reading through property EnableGS1
  • Use BarcodeScanner.Scan() method to scan gs1 barcode image file, and return all GS1-128 barcode information

            ScanOptions opts = new ScanOptions(BarcodeType.Code128);
            opts.EnableGS1 = true;

            BarcodeDetail[] result = BarcodeScanner.Scan("C://Input//gs1-sample.png", opts);
            foreach (BarcodeDetail b in result)
            {
                //  Indicate if the barcode is conform to GS1 specification.
                if (b.IsGS1Compitable)
                {
                    //  Get message in string format.
                    //  Eg. "(415)5412345678908(3911)710125"
                    String msg = b.GetMessage();
                    Console.WriteLine("Data: '{0}'", b.Data);
                    Console.WriteLine("Message: {0}", msg);
                }
            }




Scanning multiple barcodes in C# Windows application

Top


Barcodes can be scanned and read from multiple image files, and the scanned barcodes can be in multiple barcode formats. The following C# sample code allows you to scan, read multiple barcodes with different formats from multiple image files.

  • Create ScanOptions object with QR Code and Code 128 scanning supported
  • Create a list of barcode image files
  • Use BarcodeScanner.Scan() method to scan specified barcode formats on the list of image files
  • Now you will get a list of scanned barcodes in BarcodeDetail objects. Explore each object to get barcode text, barcode format, it source file path

            ScanOptions opts = new ScanOptions(new List<BarcodeType> { 
                BarcodeType.QRCode, BarcodeType.Code128 });

            String[] sourceImageFiles = new String[] {
                        "SourceImage01.png",
                        "SourceImage02.png"
            };

            BarcodeDetail[] datas = BarcodeScanner.Scan(sourceImageFiles, opts);

            foreach (BarcodeDetail obj in datas)
            {
                Console.WriteLine("Message: '" + obj.GetMessage() + "'");
                //  Show index and file path of the source image in the input array.
                //  SourceFilePath is empty if the input is file streams or Bitmap objects.
                Console.WriteLine(" Source: Index=" + obj.SourceIndex + "; Source Path: " + obj.SourceFilePath);
                Console.WriteLine(" Barcode Text: " + obj.Data + "; Format: " + obj.Type);
            }




Improve Barcode Scanner reading performance in C#

Top


Barcode Scanner library provides several barcode scanning options to allow C# developers to improve barcode reading performance in C# Windows application.
  • Crop regsions
  • Multi-threading

Scan barcodes from defined regions for faster read


One efficient way to improve barcode reading speed is to scan partial area of the image file. Barcode Reader library allows you to define regions inside the image file, and the library will only scan barcodes from the specified regions.

The C# sample code below shows how to scan QR Codes from the specified rectangle regions inside the image.

            List<SRegion> regions = new List<SRegion>();
            regions.Add(new SRegion(0, 0, 50, 60));
            regions.Add(new SRegion(100, 100, 50, 60));

            string[] barcodes = BarcodeScanner.ScanRegions("qrcode-barcodes.png", BarcodeType.QRCode, regions);


Scan barcodes using multithreading in C#


By leveraging multi-threading barcode reading in C#, barcode scanner library can execute multiple barcode scanning and processing tasks simultaneously, making barcode scanning faster and more efficient.

Here we will demostrate how to scan barcodes in multithread in C# Windows application.
  • Initialize ScanOptions object to scan QR Code
  • Customize barcode scanner option to enable 3 threads to scan QR Codes
  • Use BarcodeScanner.Scan() method to execute barcode scanning in multithread, and return the scanned barcodes

            ScanOptions options = new ScanOptions(BarcodeType.QRCode);
            //  Set maximum number of threads could be used in the scanning.
            //  The valud must be non-negative.
            //  0: disable multi-thread (Default Value)
            //  >0: using multi-thread
            options.SetMaxMultiThreadCount(3);
            BarcodeDetail[] result = BarcodeScanner.Scan(
                new String[] {
                    "SourceImage01.png",
                    "SourceImage02.png",
                    "SourceImage03.png"
                }, options);




Conclusion

Top


Now we have built a new Windows Forms app with barcode scanner functions enabled. OnBarcode C# Barcode Scanner and C# Barcode Generator is a mature and high performance barcode software for barcode scanning and reading. It allows you to quickly integrate barcode scanner features in Windows apps and also supports various barcode scanner customization options to improve the reading performance, such as regions scanning, multi-barcode reading, and multithreading barcode reading in C# applications.

OnBarcode also provides other step-by-step how-to C# tutorials to scan, read QR Code and other barcodes from image files and PDF, Office Word documents in other .NET project templates: After you have integrated the C# Barcode Reader library into your .NET project, you can further customize the barcode reading performance and handle the complex barcode data message. View details here: How to read barcodes using C#?




Common Asked Questions

How to read barcodes from images in C# Windows Forms app?

You can use OnBarcode C# Barcode Reader library to scan and read barcodes from images in C# Windows Forms app. First, you can download and install barcode library from onbarcode web site or nuget package. Then you can use Scan() method in BarcodeScanner class to read, scan 2d, 1d barcodes from image files. You can also use ScanOptions object to further customize the barcode scanning performance in C# WinForms project.

How can I scan and read barcdoes from multi-page tiff and pdf files in C# WinForms application?

You can scan and read barcodes from multi-page TIFF image file or multiple page PDF document using C# Barcode Reader library and RasterEdge XDoc.TIFF and XDoc.PDF sdk in your Windows Forms application.

What methods are available to scan and recognize multiple barcodes in a single image file in .NET WinForms project?

In C# WinForms project, you can scan and extract multiple barcodes from a single image file by providing multiple selected barcode formats to Scan method. The barcode reader library will scan and detect all specified barcode formats from one image file.

What are the barcode scanning options to improve barcode reading speed and barcode recognition rate in C# WinForms desktop application?

OnBarcode C# Barcode Reader library provides advanced barcode scanning options through ScanOptions. It allows you to adjust image scanning interval, barcode scanning directions, define barcode scanning specific areas and enable multi-thread barcode scanning in C# Windows applications.

Can I resize the barcode image or partial scan the image using C# in Windows application?

In C# WinForms class, you can easily resize the barcode image, and select the specific image areas to scanning. It will improve the barcode reading speed in your Windows application.

Does C# barcode reader library support all modern barcode formats?

The C# barcode library supports most popular 2d and 1d barcode types: QR Code, Data Matrix, PDF417, Codabar, Code 39 (with extension), Code 128, GS1-128, EAN-13, EAN-8, UPC-A, UPC-E with add-ons, ITF14, Interleaved 2 of 5, Intelligent Mail barcode.

How to build a barcode scanner desktop application using C# Barcode library?

With C# Barcode Scanner library installed, you can quickly build a barcode scanner enabled Windows Forms application using C#. Use Scan method to read, detect and extract the barcode data from images or PDF, Offcie documents. You can also further customize the barcode scanning process by using ScanOptions options.




































Terms of Use | Privacy Policy
Copyright © OnBarcode.com . All rights reserved.