Skip to footer content
USING IRONBARCODE

How to Create a C# USB Barcode Scanner

If you’ve ever worked in retail, warehousing, or inventory management, you know how crucial barcode scanners are for keeping operations running smoothly. With the IronBarcode library and its powerful validation and generation capabilities, you can build a robust C# USB barcode scanner application that goes beyond simple barcode data capture. It can also validate your barcode data, extract structured information, and even generate new barcodes on the fly.

In this guide, I’ll show you how to integrate USB barcode scanners with IronBarcode in C#. By the end, you’ll have a robust, real-time scanning solution that works with both .NET Framework and .NET applications, helping you manage inventory and track items more efficiently.

How Do USB Barcode Scanners Work with IronBarcode?

Most USB barcode scanners operate in HID (Human Interface Device) keyboard wedge mode, meaning they emulate keyboard input, allowing users to scan codes effortlessly. When you scan a barcode, the scanner "types" the barcode data followed by an Enter key. IronBarcode enhances this raw input by validating formats, extracting structured data, and enabling immediate barcode generation in response to scans.

// Capture scanner input and validate with IronBarcode
private void txtBarcode_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        string scannedData = txtBarcode.Text;
        var results = BarcodeReader.Read(GenerateBarcodeImage(scannedData));
        if (results.Any())
        {
            ProcessValidBarcode(results.First());
        }
    }
}
// Capture scanner input and validate with IronBarcode
private void txtBarcode_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        string scannedData = txtBarcode.Text;
        var results = BarcodeReader.Read(GenerateBarcodeImage(scannedData));
        if (results.Any())
        {
            ProcessValidBarcode(results.First());
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code captures scanner input through a TextBox and uses IronBarcode to validate the scanned data by attempting to read it as a valid barcode format, giving you complete control over the input.

How to Set Up Your Barcode Scanner Project?

Start by creating a Windows Forms application in Microsoft Visual Studio and ensure you download the IronBarcode library. Then install the IronBarcode library through the NuGet Package Manager Console by running this command:

Install-Package BarCode

Add these essential namespaces to your form, along with the samples provided in the documentation.

using IronBarCode;
using System.Drawing;
using System.Linq;
using IronBarCode;
using System.Drawing;
using System.Linq;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Create a simple form with a single text box for capturing scanner input, ensuring the port configuration is set correctly. Set the TextBox to automatically receive focus when the form loads, ensuring your USB scanner data is always captured.

How to Validate Scanned Barcodes with IronBarcode?

IronBarcode excels at validating and parsing barcode data. Here's how to verify scanned input and extract meaningful information:

private void ProcessScannedBarcode(string scannedText)
{
    // Generate temporary barcode image from scanned text
    var barcode = BarcodeWriter.CreateBarcode(scannedText, BarcodeEncoding.Code128);
    // Validate by reading back
    var validationResults = BarcodeReader.Read(barcode.ToBitmap());
    if (validationResults.Any())
    {
        var validated = validationResults.First();
        // Extract barcode type and value
        string format = validated.BarcodeType.ToString();
        string value = validated.Value;
        lblStatus.Text = $"Valid {format}: {value}";
        // Process based on format
        if (format.Contains("EAN") || format.Contains("UPC"))
        {
            // Product barcode - lookup item
            ProcessProductCode(value);
        }
    }
    else
    {
        lblStatus.Text = "Invalid barcode format";
    }
}
private void ProcessScannedBarcode(string scannedText)
{
    // Generate temporary barcode image from scanned text
    var barcode = BarcodeWriter.CreateBarcode(scannedText, BarcodeEncoding.Code128);
    // Validate by reading back
    var validationResults = BarcodeReader.Read(barcode.ToBitmap());
    if (validationResults.Any())
    {
        var validated = validationResults.First();
        // Extract barcode type and value
        string format = validated.BarcodeType.ToString();
        string value = validated.Value;
        lblStatus.Text = $"Valid {format}: {value}";
        // Process based on format
        if (format.Contains("EAN") || format.Contains("UPC"))
        {
            // Product barcode - lookup item
            ProcessProductCode(value);
        }
    }
    else
    {
        lblStatus.Text = "Invalid barcode format";
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This method validates the scanned code's input by creating a barcode and reading it back with IronBarcode, which serves as a reliable reference. It identifies the barcode format (e.g., Code 128, EAN, UPC) and processes accordingly. IronBarcode supports numerous formats, including QR codes, Data Matrix, PDF417, and all common 1D barcodes.

How to Generate Response Barcodes from Scanned Input?

Transform scanned data into new barcodes for labeling, tracking, or inventory management:

private void GenerateInventoryLabel(string productCode)
        {
            // Create inventory code from scanned product
            string inventoryCode = $"INV-{DateTime.Now:yyyyMMdd}-{productCode}";
            // Generate new barcode with custom styling
            var inventoryBarcode = BarcodeWriter.CreateBarcode(inventoryCode, BarcodeEncoding.Code128);
            inventoryBarcode.AddAnnotationTextAboveBarcode(inventoryCode);
            inventoryBarcode.ResizeTo(300, 100);
            // Ensure labels folder exists
            System.IO.Directory.CreateDirectory("labels");
            // Save barcode PNG for printing
            string filePath = $"labels\\{inventoryCode}.png";
            inventoryBarcode.SaveAsPng(filePath);
            // Load a copy into the PictureBox
            if (pictureBoxReceipt.Image != null)
                pictureBoxReceipt.Image.Dispose();
            pictureBoxReceipt.Image = new System.Drawing.Bitmap(filePath);
        }
        // Alternative: Generate QR code for mobile scanning
        private void CreateQRResponse(string data)
        {
            var qrCode = QRCodeWriter.CreateQrCode(data);
            qrCode.ResizeTo(200, 200);
            System.IO.Directory.CreateDirectory("labels");
            string filePath = $"labels\\QR_{DateTime.Now:yyyyMMddHHmmss}.png";
            qrCode.SaveAsPng(filePath);
            if (pictureBoxQR.Image != null)
                pictureBoxQR.Image.Dispose();
            pictureBoxQR.Image = new System.Drawing.Bitmap(filePath);
        }
private void GenerateInventoryLabel(string productCode)
        {
            // Create inventory code from scanned product
            string inventoryCode = $"INV-{DateTime.Now:yyyyMMdd}-{productCode}";
            // Generate new barcode with custom styling
            var inventoryBarcode = BarcodeWriter.CreateBarcode(inventoryCode, BarcodeEncoding.Code128);
            inventoryBarcode.AddAnnotationTextAboveBarcode(inventoryCode);
            inventoryBarcode.ResizeTo(300, 100);
            // Ensure labels folder exists
            System.IO.Directory.CreateDirectory("labels");
            // Save barcode PNG for printing
            string filePath = $"labels\\{inventoryCode}.png";
            inventoryBarcode.SaveAsPng(filePath);
            // Load a copy into the PictureBox
            if (pictureBoxReceipt.Image != null)
                pictureBoxReceipt.Image.Dispose();
            pictureBoxReceipt.Image = new System.Drawing.Bitmap(filePath);
        }
        // Alternative: Generate QR code for mobile scanning
        private void CreateQRResponse(string data)
        {
            var qrCode = QRCodeWriter.CreateQrCode(data);
            qrCode.ResizeTo(200, 200);
            System.IO.Directory.CreateDirectory("labels");
            string filePath = $"labels\\QR_{DateTime.Now:yyyyMMddHHmmss}.png";
            qrCode.SaveAsPng(filePath);
            if (pictureBoxQR.Image != null)
                pictureBoxQR.Image.Dispose();
            pictureBoxQR.Image = new System.Drawing.Bitmap(filePath);
        }
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These methods demonstrate IronBarcode's generation capabilities, creating formatted barcodes with annotations and custom sizing. The QR code generation showcases IronBarcode's support for 2D formats.

How to Create a C# USB Barcode Scanner: Figure 2

How to Build a Complete Barcode Scanning Application?

Here's a complete example combining scanning, validation, and generation:

using IronBarCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UsbBarcodeScanner
{
    public partial class InventoryScanner : Form
    {
        private List<string> scannedItems = new List<string>();
        public InventoryScanner()
        {
            InitializeComponent();
            // Wire the KeyDown event handler for scanner input
        txtScanner.KeyDown += txtScanner_KeyDown;
            // Focus the scanner TextBox when form loads
            this.Load += (s, e) => txtScanner.Focus();
        }
        private void txtScanner_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true; // Prevents ding or extra chars
                string input = txtScanner.Text.Trim();
                if (string.IsNullOrEmpty(input))
                {
                    lblStatus.Text = "Please enter a barcode";
                    return;
                }
                try
                {
                    // Generate barcode (Code128)
                    var testBarcode = BarcodeWriter.CreateBarcode(input, BarcodeEncoding.Code128);
                    // Add to inventory
                    scannedItems.Add(input);
                    listBoxInventory.Items.Add($"{DateTime.Now:HH:mm:ss} - {input}");
                    // Generate receipt barcode
                    GenerateReceipt();
                    lblStatus.Text = "Item added successfully";
                }
                catch (Exception ex)
                {
                    lblStatus.Text = $"Error: {ex.Message}";
                    // Fallback: Try IronBarcode's image or PDF scanning
                    try
                    {
                        string backupFile = "backup.pdf"; // path to backup PDF
                        if (File.Exists(backupFile))
                        {
                            var results = BarcodeReader.ReadPdf(backupFile);
                            if (results.Any())
                            {
                                var first = results.First();
                                scannedItems.Add(first.Value);
                                listBoxInventory.Items.Add($"{DateTime.Now:HH:mm:ss} - {first.Value}");
                                GenerateReceipt();
                                lblStatus.Text = "Item added via PDF fallback";
                            }
                            else
                            {
                                lblStatus.Text += " (No barcodes found in backup PDF)";
                            }
                        }
                        else
                        {
                            lblStatus.Text += " (Backup PDF not found)";
                        }
                    }
                    catch (Exception fallbackEx)
                    {
                        lblStatus.Text += $" (Fallback failed: {fallbackEx.Message})";
                    }
                }
            }
            txtScanner.Clear();
            txtScanner.Focus();
        }
        private void GenerateReceipt()
        {
            string receiptCode = $"RCP{scannedItems.Count:D5}";
            var receipt = BarcodeWriter.CreateBarcode(receiptCode, BarcodeEncoding.Code93);
            receipt.AddAnnotationTextBelowBarcode($"Items: {scannedItems.Count}");
            // Ensure labels folder exists
            Directory.CreateDirectory("labels");
            string filePath = $"labels\\{receiptCode}.png";
            // Save barcode to file
            receipt.SaveAsPng(filePath);
            // Load into PictureBox safely
            if (pictureBoxReceipt.Image != null)
                pictureBoxReceipt.Image.Dispose();
            pictureBoxReceipt.Image = new Bitmap(filePath);
        }
    }
}
using IronBarCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UsbBarcodeScanner
{
    public partial class InventoryScanner : Form
    {
        private List<string> scannedItems = new List<string>();
        public InventoryScanner()
        {
            InitializeComponent();
            // Wire the KeyDown event handler for scanner input
        txtScanner.KeyDown += txtScanner_KeyDown;
            // Focus the scanner TextBox when form loads
            this.Load += (s, e) => txtScanner.Focus();
        }
        private void txtScanner_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true; // Prevents ding or extra chars
                string input = txtScanner.Text.Trim();
                if (string.IsNullOrEmpty(input))
                {
                    lblStatus.Text = "Please enter a barcode";
                    return;
                }
                try
                {
                    // Generate barcode (Code128)
                    var testBarcode = BarcodeWriter.CreateBarcode(input, BarcodeEncoding.Code128);
                    // Add to inventory
                    scannedItems.Add(input);
                    listBoxInventory.Items.Add($"{DateTime.Now:HH:mm:ss} - {input}");
                    // Generate receipt barcode
                    GenerateReceipt();
                    lblStatus.Text = "Item added successfully";
                }
                catch (Exception ex)
                {
                    lblStatus.Text = $"Error: {ex.Message}";
                    // Fallback: Try IronBarcode's image or PDF scanning
                    try
                    {
                        string backupFile = "backup.pdf"; // path to backup PDF
                        if (File.Exists(backupFile))
                        {
                            var results = BarcodeReader.ReadPdf(backupFile);
                            if (results.Any())
                            {
                                var first = results.First();
                                scannedItems.Add(first.Value);
                                listBoxInventory.Items.Add($"{DateTime.Now:HH:mm:ss} - {first.Value}");
                                GenerateReceipt();
                                lblStatus.Text = "Item added via PDF fallback";
                            }
                            else
                            {
                                lblStatus.Text += " (No barcodes found in backup PDF)";
                            }
                        }
                        else
                        {
                            lblStatus.Text += " (Backup PDF not found)";
                        }
                    }
                    catch (Exception fallbackEx)
                    {
                        lblStatus.Text += $" (Fallback failed: {fallbackEx.Message})";
                    }
                }
            }
            txtScanner.Clear();
            txtScanner.Focus();
        }
        private void GenerateReceipt()
        {
            string receiptCode = $"RCP{scannedItems.Count:D5}";
            var receipt = BarcodeWriter.CreateBarcode(receiptCode, BarcodeEncoding.Code93);
            receipt.AddAnnotationTextBelowBarcode($"Items: {scannedItems.Count}");
            // Ensure labels folder exists
            Directory.CreateDirectory("labels");
            string filePath = $"labels\\{receiptCode}.png";
            // Save barcode to file
            receipt.SaveAsPng(filePath);
            // Load into PictureBox safely
            if (pictureBoxReceipt.Image != null)
                pictureBoxReceipt.Image.Dispose();
            pictureBoxReceipt.Image = new Bitmap(filePath);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This full-featured scanner application effortlessly captures input from your USB barcode scanner, validates each entry using IronBarcode, and maintains a real-time inventory list, enabling you to claim accuracy in your data. It automatically generates receipt barcodes for every scanned item, giving you instant visual feedback. As a safety net, IronBarcode can also read barcodes from PDFs if the hardware scanner fails. For advanced scenarios or troubleshooting, explore community discussions on Stack Overflow or dive into Microsoft’s HID device documentation.

How to Create a C# USB Barcode Scanner: Figure 3 - Output of complete scanner application with receipt barcode

Error Handling Best Practices

When working with USB scanners and IronBarcode:

  • Invalid Format: Catch exceptions when BarcodeWriter encounters unsupported data
  • Scanner Disconnection: Implement TextBox focus management to handle scanner removal
  • Data Validation: Use IronBarcode's format-specific encodings to ensure data compatibility
  • Generation Failures: Wrap barcode generation in try-catch blocks
  • Timeout Handling: Consider implementing keystroke timing to differentiate scanner from keyboard input

Conclusion

IronBarcode transforms simple USB barcode scanning into intelligent data processing applications that efficiently filter and manage data. By combining hardware scanner input with IronBarcode's validation, generation, and format conversion capabilities, you can build robust scanning solutions for any industry. Need to handle high-volume scanning? Consider the licensing options that best fit your deployment needs.

Start your free trial to implement professional barcode scanning in your C# applications today.

Frequently Asked Questions

What is IronBarcode and how does it relate to USB barcode scanners?

IronBarcode is a library that enables developers to build robust C# applications for USB barcode scanning. It offers features like barcode validation, data extraction, and barcode generation.

Can IronBarcode validate barcode data from a USB scanner?

Yes, IronBarcode can validate barcode data captured from a USB scanner, ensuring data integrity and accuracy in your C# applications.

How does IronBarcode handle barcode generation?

IronBarcode can generate new barcodes on the fly, allowing developers to create and print barcodes easily within their C# applications.

Is there error handling support in IronBarcode for USB barcode scanning?

Yes, IronBarcode includes comprehensive error handling to manage common issues that may arise during USB barcode scanning and processing.

What types of barcodes can be scanned using IronBarcode?

IronBarcode supports scanning a wide range of barcode symbologies, including QR codes, UPC, Code 39, and more, making it versatile for various applications.

Can IronBarcode extract structured information from scanned barcodes?

Yes, IronBarcode can extract structured information from scanned barcodes, aiding in efficient data processing and management.

How can I get started with building a USB barcode scanner application in C#?

To start building a USB barcode scanner application in C#, you can utilize IronBarcode along with the provided code examples and documentation to guide your development process.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...Read More
Ready to Get Started?
Nuget Downloads 1,864,749 | Version: 2025.9 just released