What is Barcode Scanner?
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.
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#
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.
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.
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.
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:
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
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.
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.
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".
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#
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
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#
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.
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.
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
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:
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:
- How to read barcodes in C# ASP.NET web app?
- How to read barcodes in C# ASP.NET MVC web app?
- How to read barcodes in ASP.NET framework web application?
- How to read barcodes in C# WPF Windows app?
