跳過到頁腳內容
使用IRONBARCODE

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

如果你曾經從事過零售、倉儲或庫存管理工作,你就會知道條碼掃描器對於保持營運順利進行有多麼重要。 借助 IronBarcode 庫及其強大的驗證和生成功能,您可以建立一個強大的 C# USB 條碼掃描器應用程序,其功能遠不止於簡單的條碼資料擷取。 它還可以驗證條碼數據,提取結構化訊息,甚至可以即時產生新的條碼。

在本指南中,我將向您展示如何在 C# 中將 USB 條碼掃描器與 IronBarcode 整合。 最終,您將擁有一個強大的即時掃描解決方案,可與 .NET Framework 和 .NET 應用程式搭配使用,協助您更有效率地管理庫存和追蹤物品。

USB條碼掃描器如何與IronBarcode搭配使用?

大多數 USB 條碼掃描器以 HID(人機介面裝置)鍵盤楔形模式運行,這意味著它們模擬鍵盤輸入,使用戶能夠輕鬆掃描條碼。 掃描條碼時,掃描器會"輸入"條碼數據,然後按 Enter 鍵。 IronBarcode 透過驗證格式、提取結構化資料以及回應掃描立即產生條碼來增強這種原始輸入

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

這段程式碼透過文字方塊擷取掃描器輸入,並使用 IronBarcode 來驗證掃描的數據,嘗試將其讀取為有效的條碼格式,使您能夠完全控制輸入。

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

首先在 Microsoft Visual Studio 中建立一個 Windows Forms 應用程序,並確保下載 IronBarcode 庫。 然後透過 NuGet 套件管理器控制台執行以下命令來安裝 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

建立一個簡單的表單,其中包含一個用於擷取掃描器輸入的文字框,並確保連接埠配置設定正確。 將文字方塊設定為在表單載入時自動取得焦點,以確保始終擷取 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 讀取該條碼來驗證掃描代碼的輸入,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 的產生功能,可以建立帶有註解和自訂尺寸的格式化條碼。 二維碼產生功能展示了 IronBarcode 對二維格式的支援。

如何建立 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 讀取條碼。 對於進階場景或故障排除,請瀏覽Stack Overflow上的社群討論或深入了解Microsoft 的 HID 裝置文件

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

錯誤處理最佳實踐

使用 USB 掃描器和 IronBarcode 時:

*無效格式*:擷取 BarcodeWriter 遇到不支援的資料時引發的異常 掃描器斷開連線:實現文字方塊焦點管理以處理掃描器移除操作 資料驗證:使用 IronBarcode 的特定格式編碼,以確保資料相容性 產生失敗**:將條碼產生過程封裝在 try-catch 區塊中。 *超時處理:考慮實現按鍵計時,以區分掃描器輸入和鍵盤輸入。

結論

IronBarcode 將簡單的 USB 條碼掃描轉換為智慧資料處理應用程序,可有效篩選和管理資料。 透過將硬體掃描器輸入與 IronBarcode 的驗證、產生和格式轉換功能結合,您可以為任何行業建立強大的掃描解決方案。 需要處理大量掃描任務? 請根據您的部署需求選擇最合適的授權選項

立即開始免費試用,在您的 C# 應用程式中實現專業的條碼掃描功能。

常見問題解答

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

IronBarcode 是一個函式庫,可讓開發人員建立強大的 USB 條碼掃描 C# 應用程式。它提供條碼驗證、資料擷取和條碼產生等功能。

IronBarcode 可以驗證 USB 掃描器的條碼資料嗎?

是的,IronBarcode 可以驗證從 USB 掃描器擷取的 BarCode 資料,確保您 C# 應用程式中資料的完整性與正確性。

IronBarcode 如何處理條碼生成?

IronBarcode 能夠即時產生新的條碼,讓開發人員在 C# 應用程式中輕鬆建立和列印條碼。

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

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

使用 IronBarcode 可以掃描哪些類型的 BarCode?

IronBarcode 支援掃描多種條碼符號,包括 QR 碼、UPC、Code 39 等,使其成為各種應用程式的通用工具。

IronBarcode 可以從掃描的 BarCode 中提取結構化資訊嗎?

是的,IronBarcode 可以從掃描的 BarCode 中萃取結構化的資訊,協助有效率的資料處理與管理。

如何開始使用 C# 建立 USB BarCode 掃描器應用程式?

要開始在 C# 中建立 USB 條碼掃描器應用程式,您可以利用 IronBarcode 以及所提供的程式碼範例和文件來引導您的開發過程。

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