跳過到頁腳內容
使用IRONBARCODE

如何在C#中創建USB條碼掃描器

如果您曾在零售、倉儲或庫存管理領域工作過,您就會知道條碼掃描器對保持運營順暢運行是多麼重要。 通過IronBarcode庫及其強大的驗證和生成功能,您可以構建一個強大的C# USB條碼掃描應用程序,超越簡單的條碼數據捕獲。 它還可以驗證您的條碼數據,提取結構化信息,甚至即時生成新條碼。

在本指南中,我將向您展示如何將USB條碼掃描器與IronBarcode集成到C#中。 到最後,您將擁有一個穩健的實時掃描解決方案,適用於.NET框架和.NET應用程序,幫助您更高效地管理庫存和追踪物品。

USB條碼掃描器如何與IronBarcode一起工作?

大多數USB條碼掃描器以HID(人機介面設備)鍵盤楔入模式運行,表示它們模擬鍵盤輸入,使用戶能夠輕鬆掃描代碼。 當您掃描條碼時,掃描器會"鍵入"條碼數據,然後按下Enter鍵。 IronBarcode enhances this raw input by validating formats, extracting structured data, and enabling immediate 條碼生成

// 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

這段代碼通過TextBox捕捉掃描器的輸入,並使用IronBarcode驗證掃描數據,嘗試將其讀取為有效的條碼格式,讓您對輸入具備完全控制權。

如何設置條碼掃描器項目?

首先在Microsoft Visual Studio中創建一個Windows Forms應用程序,並確保下載IronBarcode庫。 然後通過運行以下命令,在NuGet Package Manager Console中安裝IronBarcode庫

Install-Package BarCode

將這些基本命名空間添加到您的表單中,以及文檔中提供的示例。

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

創建一個簡單的表單,具有單個文本框來捕捉掃描器輸入,確保端口配置正確。 設置TextBox,以便表單加載時自動獲得焦點,確保USB掃描器數據始終被捕獲。

如何使用IronBarcode驗證掃描到的條碼?

IronBarcode擅長驗證和解析條碼數據。 以下是驗證掃描輸入並提取有意義信息的方法:

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

此方法通過創建條碼並使用IronBarcode讀取回來,驗證掃描代碼的輸入,這作為可靠的參考。 它確定條碼格式(例如,Code 128、EAN、UPC)並相應處理。 IronBarcode支持多種格式,包括QR碼、Data Matrix、PDF417和所有常見的1D條碼。

如何從掃描到的輸入生成響應條碼?

將掃描數據轉換為新條碼,用於標籤、跟踪或庫存管理:

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

這些方法演示了IronBarcode的生成能力,創建帶有註釋和自定義大小的格式化條碼。 QR碼生成展示了IronBarcode對2D格式的支持。

如何創建C# USB條碼掃描器:圖2

如何建立完整的條碼掃描應用程序?

這是將掃描、驗證和生成結合起來的一個完整示例:

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

這個全功能的掃描器應用程序能夠輕鬆地捕捉USB條碼掃描器的輸入,使用IronBarcode驗證每個條目,並維護實時庫存清單,使您能夠聲稱數據的準確性。 它自動為每個掃描項生成收據條碼,提供即時視覺反饋。 IronBarcode作為安全網,如果硬件掃描器失敗,也能夠從PDF中讀取條碼。 For advanced scenarios or troubleshooting, explore community discussions on Stack Overflow or dive into Microsoft’s HID device documentation.

如何創建C# USB條碼掃描器:圖3 - 包含收據條碼的完整掃描器應用程序的輸出

錯誤處理最佳實踐

在使用USB掃描器和IronBarcode時:

  • 格式無效:當BarcodeWriter遇到不支持的數據時捕捉異常
  • 掃描器斷開:實現TextBox焦點管理來處理掃描器移除
  • 數據驗證:使用IronBarcode的格式特定編碼以確保數據兼容性
  • 生成失敗:在try-catch塊中包裹條碼生成
  • 超時處理:考慮實現按鍵時間來區分掃描器和鍵盤輸入

結論

IronBarcode將簡單的USB條碼掃描轉變為智能數據處理應用程序,能夠高效地過濾和管理數據。 通過將硬件掃描器輸入與IronBarcode的驗證、生成和格式轉換功能結合起來,您可以為任何行業構建強大的掃描解決方案。 需要處理高頻次的掃描? 考慮最符合您部署需求的授權選項

開始您的免費試用,以便在您的C#應用程序中實施專業條碼掃描。

常見問題解答

什麼是 IronBarcode,它與 USB 條碼掃描器有何關係?

IronBarcode 是一個函式庫,使開發人員能夠構建用於 USB 條碼掃描的強大 C# 應用程式。它提供了條碼驗證、數據提取和條碼生成等功能。

IronBarcode 可以驗證來自 USB 掃描器的條碼數據嗎?

是的,IronBarcode 可以驗證從 USB 掃描器截取的條碼數據,確保 C# 應用程式中的數據完整性和準確性。

IronBarcode 如何處理條碼生成?

IronBarcode 可以即時生成新的條碼,使開發人員能夠在其 C# 應用程式中輕松創建和打印條碼。

IronBarcode 是否支持 USB 條碼掃描的錯誤處理?

是的,IronBarcode 包含全面的錯誤處理,以管理 USB 條碼掃描和處理過程中可能出現的常見問題。

IronBarcode 可以掃描哪些類型的條碼?

IronBarcode 支持掃描各種條碼符號,包括 QR 碼、UPC、Code 39 等,這使其在各種應用中具有多功能性。

IronBarcode 能夠提取掃描條碼中的結構化信息嗎?

是的,IronBarcode 可以從掃描的條碼中提取結構化信息,協助高效數據處理和管理。

我如何開始在 C# 中構建 USB 條碼掃描器應用程式?

要開始在 C# 中構建 USB 條碼掃描器應用程序,您可以利用 IronBarcode,並結合提供的代碼示例和文檔來指導您的開發過程。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。