Saltar al pie de página
USO DE IRONBARCODE

Cómo Crear un Escáner de Códigos de Barras USB en C#

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.

Preguntas Frecuentes

¿Qué es IronBarcode y cómo se relaciona con los escáneres de código de barras USB?

IronBarcode es una biblioteca que permite a los desarrolladores construir aplicaciones robustas de C# para escaneo de códigos de barras USB. Ofrece funciones como validación de códigos de barras, extracción de datos y generación de códigos de barras.

¿Puede IronBarcode validar datos de código de barras de un escáner USB?

Sí, IronBarcode puede validar datos de códigos de barras capturados desde un escáner USB, asegurando la integridad y precisión de los datos en tus aplicaciones C#.

¿Cómo maneja IronBarcode la generación de códigos de barras?

IronBarcode puede generar nuevos códigos de barras al instante, permitiendo a los desarrolladores crear e imprimir códigos de barras fácilmente dentro de sus aplicaciones C#.

¿Existe soporte para manejo de errores en IronBarcode para el escaneo de códigos de barras USB?

Sí, IronBarcode incluye un manejo de errores completo para gestionar problemas comunes que pueden surgir durante la escaneo y proceso de códigos de barras USB.

¿Qué tipos de códigos de barras se pueden escanear con IronBarcode?

IronBarcode admite el escaneo de una amplia gama de simbologías de códigos de barras, incluyendo códigos QR, UPC, Código 39 y más, lo que lo hace versátil para diversas aplicaciones.

¿Puede IronBarcode extraer información estructurada de los códigos de barras escaneados?

Sí, IronBarcode puede extraer información estructurada de los códigos de barras escaneados, ayudando en el procesamiento y gestión eficiente de datos.

¿Cómo puedo comenzar a construir una aplicación de escáner de código de barras USB en C#?

Para comenzar a construir una aplicación de escáner de código de barras USB en C#, puedes utilizar IronBarcode junto con los ejemplos de código y la documentación proporcionada para guiar tu proceso de desarrollo.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más