USING IRONBARCODE How to Create a C# USB Barcode Scanner Jordi Bardia 已发布:九月 29, 2025 Download IronBarcode NuGet 下载 DLL 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 如果您曾在零售、仓储或库存管理工作过,您就会知道条码扫描仪对于保持操作顺利进行是多么重要。 利用IronBarcode库和其强大的验证和生成功能,您可以构建一个强大的C# USB条码扫描仪应用程序,超越简单的条码数据捕获。 它还可以验证您的条码数据,提取结构化信息,甚至即时生成新的条码。 在本指南中,我将向您展示如何在C#中将USB条码扫描仪与IronBarcode集成。 最后,您将拥有一个强大、实时的扫描解决方案,兼容 .NET Framework 和 .NET 应用程序,帮助您更有效地管理库存和跟踪物品。 USB条码扫描仪如何与IronBarcode一起工作? 大多数USB条码扫描仪在HID(人机界面设备)键盘楔形模式下操作,意味着它们模拟键盘输入,允许用户轻松扫描代码。 当您扫描条码时,扫描仪 "键入" 条码数据并跟随回车键。 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包管理器控制台运行以下命令安装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及所有常见的一维条码的多种格式。 如何从扫描的输入生成响应条码? 将扫描的数据转化为新的条码用于标签、跟踪或库存管理: 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对二维格式的支持。 如何构建完整的条码扫描应用程序? 这是一个结合扫描、验证和生成的完整示例: 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. 错误处理最佳实践 处理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 支持扫描广泛的条码符号体系,包括二维码、UPC、Code 39 等,使其适用于各种应用程序。 IronBarcode 能否从扫描的条码中提取结构化信息? 是的,IronBarcode 可以从扫描的条码中提取结构化信息,有助于高效的数据处理和管理。 如何开始在 C# 中构建 USB 条码扫描器应用程序? 要开始在 C# 中构建 USB 条码扫描器应用程序,您可以利用 IronBarcode 以及提供的代码示例和文档来指导您的开发过程。 Jordi Bardia 立即与工程团队聊天 软件工程师 Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。 相关文章 已发布十月 19, 2025 How to Print Barcodes in Crystal Reports with VB.NET Generate and print barcodes in Crystal Reports using VB.NET. Step-by-step tutorial with IronBarcode SDK for reliable barcode integration. 阅读更多 已发布九月 29, 2025 IronBarcode vs. Open-Source Barcode Readers in .NET Learn how to read barcodes in C# using IronBarcode 阅读更多 已发布九月 29, 2025 How to Scan Barcodes in an ASP.NET Application Learn how to Scan Barcodes in ASP.NET using IronBarcode 阅读更多 How to Scan Barcodes in an ASP.NET ApplicationHow to Generate Barcodes in Xamarin...
已发布十月 19, 2025 How to Print Barcodes in Crystal Reports with VB.NET Generate and print barcodes in Crystal Reports using VB.NET. Step-by-step tutorial with IronBarcode SDK for reliable barcode integration. 阅读更多
已发布九月 29, 2025 IronBarcode vs. Open-Source Barcode Readers in .NET Learn how to read barcodes in C# using IronBarcode 阅读更多
已发布九月 29, 2025 How to Scan Barcodes in an ASP.NET Application Learn how to Scan Barcodes in ASP.NET using IronBarcode 阅读更多