C# USB 條碼掃描器:IronBarcode 整合完整指南
USB條碼掃描器可作為鍵盤輸入設備,自動將掃描資料傳送至C#應用程式。 IronBarcode處理此輸入以驗證格式、提取結構化資料並產生新的條碼,從而為庫存管理系統建立完整的掃描解決方案,且部署複雜性極低。
零售、倉儲和庫存管理作業都依賴高效的條碼掃描。 借助IronBarcode及其有效的驗證和生成功能,開發人員可以建立可靠的 USB 條碼掃描器應用程序,這些應用程式的功能不僅限於簡單的資料收集。 該庫可以驗證條碼數據,提取結構化訊息,並即時產生新的條碼。
本指南示範如何在 C# 中將 USB 條碼掃描器與IronBarcode整合。 最終成果是可與.NET Framework 和 .NET 應用程式配合使用的即時掃描解決方案,可協助團隊有效率地管理庫存和追蹤物品。 無論是建立銷售點系統還是企業庫存管理解決方案,IronBarcode 的跨平台相容性都能確保應用程式在Windows 、 Linux或macOS上流暢運作。
USB條碼掃描器如何與IronBarcode搭配使用?
為什麼鍵盤楔形模式對整合很重要?
大多數 USB 條碼掃描器以 HID 鍵盤楔形模式運行,模擬鍵盤輸入,從而輕鬆掃描條碼。 掃描條碼時,掃描器會"輸入"數據,然後按 Enter 鍵。 IronBarcode 透過驗證格式、提取結構化資料以及回應掃描立即產生條碼來改善這種原始輸入。
了解不同的掃描器通訊模式有助於企業應用。 專業掃描器除了鍵盤楔形模式外,還支援串行通訊和直接 USB HID 模式:
// Example: Handling different scanner input modes
public interface IScannerInput
{
event EventHandler<string> BarcodeScanned;
void StartListening();
void StopListening();
}
// Keyboard wedge implementation
public class KeyboardWedgeScanner : IScannerInput
{
public event EventHandler<string> BarcodeScanned;
private readonly TextBox _inputBox;
public KeyboardWedgeScanner(TextBox inputBox)
{
_inputBox = inputBox;
_inputBox.KeyPress += OnKeyPress;
}
private void OnKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
BarcodeScanned?.Invoke(this, _inputBox.Text);
_inputBox.Clear();
}
}
public void StartListening() => _inputBox.Focus();
public void StopListening() => _inputBox.Enabled = false;
}
// Serial port implementation for professional scanners
public class SerialPortScanner : IScannerInput
{
public event EventHandler<string> BarcodeScanned;
private System.IO.Ports.SerialPort _port;
public SerialPortScanner(string portName, int baudRate = 9600)
{
_port = new System.IO.Ports.SerialPort(portName, baudRate);
_port.DataReceived += OnDataReceived;
}
private void OnDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string data = _port.ReadLine().Trim();
BarcodeScanned?.Invoke(this, data);
}
public void StartListening() => _port.Open();
public void StopListening() => _port.Close();
}// Example: Handling different scanner input modes
public interface IScannerInput
{
event EventHandler<string> BarcodeScanned;
void StartListening();
void StopListening();
}
// Keyboard wedge implementation
public class KeyboardWedgeScanner : IScannerInput
{
public event EventHandler<string> BarcodeScanned;
private readonly TextBox _inputBox;
public KeyboardWedgeScanner(TextBox inputBox)
{
_inputBox = inputBox;
_inputBox.KeyPress += OnKeyPress;
}
private void OnKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
BarcodeScanned?.Invoke(this, _inputBox.Text);
_inputBox.Clear();
}
}
public void StartListening() => _inputBox.Focus();
public void StopListening() => _inputBox.Enabled = false;
}
// Serial port implementation for professional scanners
public class SerialPortScanner : IScannerInput
{
public event EventHandler<string> BarcodeScanned;
private System.IO.Ports.SerialPort _port;
public SerialPortScanner(string portName, int baudRate = 9600)
{
_port = new System.IO.Ports.SerialPort(portName, baudRate);
_port.DataReceived += OnDataReceived;
}
private void OnDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string data = _port.ReadLine().Trim();
BarcodeScanned?.Invoke(this, data);
}
public void StartListening() => _port.Open();
public void StopListening() => _port.Close();
}開發人員如何擷取和驗證掃描器輸入?
// Capture scanner input and validate with IronBarcode
private async void ProcessScannerInput(string scannedData)
{
try
{
// Validate the scanned data format
var validationBarcode = BarcodeWriter.CreateBarcode(scannedData, BarcodeEncoding.Code128);
var results = await BarcodeReader.ReadAsync(validationBarcode.ToBitmap());
if (results.Any())
{
var result = results.First();
// Extract metadata for enterprise systems
var scanMetadata = new ScanMetadata
{
BarcodeType = result.BarcodeType,
Value = result.Value,
Confidence = result.Confidence,
ScanTimestamp = DateTime.UtcNow,
ScannerDevice = GetCurrentScannerInfo()
};
await ProcessValidBarcode(scanMetadata);
}
else
{
HandleInvalidScan(scannedData);
}
}
catch (Exception ex)
{
LogScanError(ex, scannedData);
}
}// Capture scanner input and validate with IronBarcode
private async void ProcessScannerInput(string scannedData)
{
try
{
// Validate the scanned data format
var validationBarcode = BarcodeWriter.CreateBarcode(scannedData, BarcodeEncoding.Code128);
var results = await BarcodeReader.ReadAsync(validationBarcode.ToBitmap());
if (results.Any())
{
var result = results.First();
// Extract metadata for enterprise systems
var scanMetadata = new ScanMetadata
{
BarcodeType = result.BarcodeType,
Value = result.Value,
Confidence = result.Confidence,
ScanTimestamp = DateTime.UtcNow,
ScannerDevice = GetCurrentScannerInfo()
};
await ProcessValidBarcode(scanMetadata);
}
else
{
HandleInvalidScan(scannedData);
}
}
catch (Exception ex)
{
LogScanError(ex, scannedData);
}
}這段程式碼透過各種方法捕捉掃描器輸入,並利用IronBarcode 的非同步讀取功能來驗證掃描的數據,而不會阻塞 UI 線程。 置信度閾值功能確保在生產環境中只處理高品質的掃描結果。
如何設定條碼掃描器項目?
有哪些必要的依賴項和配置?
首先,對於桌面場景,可以在 Visual Studio 中建立 Windows Forms 應用程式;對於基於 Web 的掃描應用程序,可以考慮使用Blazor 。 對於行動庫存解決方案, .NET MAUI提供出色的跨平台支持,具備Android和iOS 功能。 然後透過 NuGet 套件管理器控制台安裝 IronBarcode :
Install-Package BarCode
對於容器化部署, IronBarcode 可與 Docker 無縫協作,為企業環境提供部署清單。
快速入門:在 C# 中建立二維碼圖像
建立二維碼會產生一個可視化的影像,將資料編碼成可掃描的方塊:
立即開始使用 NuGet 建立 PDF 檔案:
使用 NuGet 套件管理器安裝 IronBarcode
複製並運行這段程式碼。
using IronBarCode; // Generate QR code from scanned inventory data string inventoryCode = "INV-2025-001"; var qrCode = BarcodeWriter.CreateQrCode(inventoryCode); // Apply styling for professional labels qrCode.ResizeTo(300, 300); qrCode.SetMargins(10); qrCode.ChangeQrCodeColor(IronSoftware.Drawing.Color.DarkBlue); // Add logo for branding qrCode.AddLogoToQrCode("company_logo.png", 60, 60); // Save as high-quality image qrCode.SaveAsPng("inventory_qr.png"); // Alternative: Save as PDF for printing qrCode.SaveAsPdf("inventory_qr.pdf");部署到您的生產環境進行測試
應用程式應該包含哪些命名空間?
請將以下必要的命名空間新增至表單中,並參考文件中的範例:
using IronBarCode;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.IO.Ports; // For serial scanners
using System.Diagnostics; // For performance monitoringusing IronBarCode;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.IO.Ports; // For serial scanners
using System.Diagnostics; // For performance monitoring開發人員應該如何配置掃描器輸入表單?
企業應用受益於支援多種掃描器品牌的靈活掃描器配置系統:
public class ScannerConfiguration
{
public string ScannerType { get; set; } // "KeyboardWedge", "Serial", "USB-HID"
public string PortName { get; set; } // For serial scanners
public int BaudRate { get; set; } = 9600;
public string Terminator { get; set; } = "\r\n";
public bool EnableBeep { get; set; } = true;
// Brand-specific settings
public Dictionary<string, string> BrandSettings { get; set; } = new();
// Common scanner brand configurations
public static ScannerConfiguration GetHoneywellConfig()
{
return new ScannerConfiguration
{
ScannerType = "Serial",
BaudRate = 115200,
BrandSettings = new Dictionary<string, string>
{
{"Prefix", "STX"},
{"Suffix", "ETX"},
{"TriggerMode", "Manual"}
}
};
}
public static ScannerConfiguration GetSymbolConfig()
{
return new ScannerConfiguration
{
ScannerType = "KeyboardWedge",
BrandSettings = new Dictionary<string, string>
{
{"ScanMode", "Continuous"},
{"BeepVolume", "High"}
}
};
}
}public class ScannerConfiguration
{
public string ScannerType { get; set; } // "KeyboardWedge", "Serial", "USB-HID"
public string PortName { get; set; } // For serial scanners
public int BaudRate { get; set; } = 9600;
public string Terminator { get; set; } = "\r\n";
public bool EnableBeep { get; set; } = true;
// Brand-specific settings
public Dictionary<string, string> BrandSettings { get; set; } = new();
// Common scanner brand configurations
public static ScannerConfiguration GetHoneywellConfig()
{
return new ScannerConfiguration
{
ScannerType = "Serial",
BaudRate = 115200,
BrandSettings = new Dictionary<string, string>
{
{"Prefix", "STX"},
{"Suffix", "ETX"},
{"TriggerMode", "Manual"}
}
};
}
public static ScannerConfiguration GetSymbolConfig()
{
return new ScannerConfiguration
{
ScannerType = "KeyboardWedge",
BrandSettings = new Dictionary<string, string>
{
{"ScanMode", "Continuous"},
{"BeepVolume", "High"}
}
};
}
}如何使用 IronBarcode 驗證掃描的條碼?
條碼驗證的最佳方法是什麼?
IronBarcode 擅長驗證和解析多種格式的條碼資料。 此函式庫支援Code 128 、 EAN-13和Code 39等一維條碼,以及QR 碼和Data Matrix等二維格式。 以下是一種改進的驗證方法:
public class BarcodeValidator
{
private readonly Dictionary<BarcodeType, Func<string, bool>> _validators;
public BarcodeValidator()
{
_validators = new Dictionary<BarcodeType, Func<string, bool>>
{
{ BarcodeType.Code128, ValidateCode128 },
{ BarcodeType.EAN13, ValidateEAN13 },
{ BarcodeType.UPCA, ValidateUPCA },
{ BarcodeType.QRCode, ValidateQRCode }
};
}
public async Task<ValidationResult> ValidateScannedBarcodeAsync(string scannedText)
{
var result = new ValidationResult();
try
{
// Attempt multiple barcode formats for flexibility
var encodings = new[] {
BarcodeEncoding.Code128,
BarcodeEncoding.EAN13,
BarcodeEncoding.UPCA,
BarcodeEncoding.QRCode
};
foreach (var encoding in encodings)
{
try
{
var barcode = BarcodeWriter.CreateBarcode(scannedText, encoding);
var validationResults = await BarcodeReader.ReadAsync(barcode.ToBitmap());
if (validationResults.Any())
{
var validated = validationResults.First();
result.IsValid = true;
result.Format = validated.BarcodeType;
result.Value = validated.Value;
result.Confidence = validated.Confidence;
// Apply format-specific validation
if (_validators.ContainsKey(validated.BarcodeType))
{
result.PassesBusinessRules = _validators___PROTECTED_LINK_35___;
}
break;
}
}
catch { /* Try next format */ }
}
// Handle GS1-128 for supply chain applications
if (!result.IsValid && IsGS1Format(scannedText))
{
result = await ValidateGS1BarcodeAsync(scannedText);
}
}
catch (Exception ex)
{
result.Error = ex.Message;
}
return result;
}
private bool ValidateEAN13(string value)
{
// EAN-13 checksum validation
if (value.Length != 13) return false;
int sum = 0;
for (int i = 0; i < 12; i++)
{
int digit = int.Parse(value[i].ToString());
sum += (i % 2 == 0) ? digit : digit * 3;
}
int checkDigit = (10 - (sum % 10)) % 10;
return checkDigit == int.Parse(value[12].ToString());
}
}public class BarcodeValidator
{
private readonly Dictionary<BarcodeType, Func<string, bool>> _validators;
public BarcodeValidator()
{
_validators = new Dictionary<BarcodeType, Func<string, bool>>
{
{ BarcodeType.Code128, ValidateCode128 },
{ BarcodeType.EAN13, ValidateEAN13 },
{ BarcodeType.UPCA, ValidateUPCA },
{ BarcodeType.QRCode, ValidateQRCode }
};
}
public async Task<ValidationResult> ValidateScannedBarcodeAsync(string scannedText)
{
var result = new ValidationResult();
try
{
// Attempt multiple barcode formats for flexibility
var encodings = new[] {
BarcodeEncoding.Code128,
BarcodeEncoding.EAN13,
BarcodeEncoding.UPCA,
BarcodeEncoding.QRCode
};
foreach (var encoding in encodings)
{
try
{
var barcode = BarcodeWriter.CreateBarcode(scannedText, encoding);
var validationResults = await BarcodeReader.ReadAsync(barcode.ToBitmap());
if (validationResults.Any())
{
var validated = validationResults.First();
result.IsValid = true;
result.Format = validated.BarcodeType;
result.Value = validated.Value;
result.Confidence = validated.Confidence;
// Apply format-specific validation
if (_validators.ContainsKey(validated.BarcodeType))
{
result.PassesBusinessRules = _validators___PROTECTED_LINK_35___;
}
break;
}
}
catch { /* Try next format */ }
}
// Handle GS1-128 for supply chain applications
if (!result.IsValid && IsGS1Format(scannedText))
{
result = await ValidateGS1BarcodeAsync(scannedText);
}
}
catch (Exception ex)
{
result.Error = ex.Message;
}
return result;
}
private bool ValidateEAN13(string value)
{
// EAN-13 checksum validation
if (value.Length != 13) return false;
int sum = 0;
for (int i = 0; i < 12; i++)
{
int digit = int.Parse(value[i].ToString());
sum += (i % 2 == 0) ? digit : digit * 3;
}
int checkDigit = (10 - (sum % 10)) % 10;
return checkDigit == int.Parse(value[12].ToString());
}
}對於多頁文檔,IronBarcode 可以讀取 PDF和多頁 TIFF 文件中的條碼。
應用程式可以驗證哪些條碼格式?
此驗證方法支援所有主流的一維條碼格式和二維條碼格式。 對於特殊應用,IronBarcode 也支援供應鏈管理中常用的MSI 條碼和GS1-128格式。
如何根據掃描的輸入產生響應條碼?
應用程式何時應該根據掃描資料建立新的條碼?
將掃描資料轉換為可用於標籤、追蹤或庫存管理的新條碼,並具備生產就緒功能。 IronBarcode 的產生功能支援從各種資料類型建立條碼。 將條碼匯出為圖像、 PDF 、 HTML或串流:
public class InventoryBarcodeGenerator
{
private readonly string _labelPath = "labels";
public InventoryBarcodeGenerator()
{
// Ensure proper licensing for production use
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
System.IO.Directory.CreateDirectory(_labelPath);
}
public async Task<GeneratedBarcode> GenerateInventoryLabelAsync(string productCode, InventoryAction action)
{
try
{
// Generate structured inventory code
var inventoryCode = GenerateStructuredCode(productCode, action);
// Create high-quality barcode with production settings
var barcode = BarcodeWriter.CreateBarcode(inventoryCode, BarcodeEncoding.Code128);
// Apply enterprise styling
barcode.ResizeTo(400, 120);
barcode.SetMargins(10);
barcode.AddAnnotationTextAboveBarcode(inventoryCode, IronSoftware.Drawing.Font.Arial, 12);
barcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.Black);
// Add data matrix for redundancy in warehouse environments
var dataMatrix = BarcodeWriter.CreateBarcode(inventoryCode, BarcodeEncoding.DataMatrix);
dataMatrix.ResizeTo(100, 100);
// Save with error handling
var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
var fileName = $"{inventoryCode}_{timestamp}";
// Save as multiple formats for flexibility
await Task.Run(() =>
{
barcode.SaveAsPng($"{_labelPath}\\{fileName}.png");
barcode.SaveAsPdf($"{_labelPath}\\{fileName}.pdf");
barcode.SaveAsSvg($"{_labelPath}\\{fileName}.svg");
});
return new GeneratedBarcode
{
Code = inventoryCode,
LinearBarcodePath = $"{_labelPath}\\{fileName}.png",
DataMatrixPath = $"{_labelPath}\\{fileName}_dm.png",
Timestamp = DateTime.UtcNow
};
}
catch (Exception ex)
{
throw new BarcodeGenerationException($"Failed to generate barcode for {productCode}", ex);
}
}
private string GenerateStructuredCode(string productCode, InventoryAction action)
{
// Implement GS1 Application Identifiers for enterprise compatibility
var ai = action switch
{
InventoryAction.Receive => "10", // Batch/Lot number
InventoryAction.Ship => "400", // Customer purchase order
InventoryAction.Count => "37", // Quantity
_ => "91" // Internal use
};
return $"({ai}){DateTime.Now:yyMMdd}{productCode}";
}
}public class InventoryBarcodeGenerator
{
private readonly string _labelPath = "labels";
public InventoryBarcodeGenerator()
{
// Ensure proper licensing for production use
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
System.IO.Directory.CreateDirectory(_labelPath);
}
public async Task<GeneratedBarcode> GenerateInventoryLabelAsync(string productCode, InventoryAction action)
{
try
{
// Generate structured inventory code
var inventoryCode = GenerateStructuredCode(productCode, action);
// Create high-quality barcode with production settings
var barcode = BarcodeWriter.CreateBarcode(inventoryCode, BarcodeEncoding.Code128);
// Apply enterprise styling
barcode.ResizeTo(400, 120);
barcode.SetMargins(10);
barcode.AddAnnotationTextAboveBarcode(inventoryCode, IronSoftware.Drawing.Font.Arial, 12);
barcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.Black);
// Add data matrix for redundancy in warehouse environments
var dataMatrix = BarcodeWriter.CreateBarcode(inventoryCode, BarcodeEncoding.DataMatrix);
dataMatrix.ResizeTo(100, 100);
// Save with error handling
var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
var fileName = $"{inventoryCode}_{timestamp}";
// Save as multiple formats for flexibility
await Task.Run(() =>
{
barcode.SaveAsPng($"{_labelPath}\\{fileName}.png");
barcode.SaveAsPdf($"{_labelPath}\\{fileName}.pdf");
barcode.SaveAsSvg($"{_labelPath}\\{fileName}.svg");
});
return new GeneratedBarcode
{
Code = inventoryCode,
LinearBarcodePath = $"{_labelPath}\\{fileName}.png",
DataMatrixPath = $"{_labelPath}\\{fileName}_dm.png",
Timestamp = DateTime.UtcNow
};
}
catch (Exception ex)
{
throw new BarcodeGenerationException($"Failed to generate barcode for {productCode}", ex);
}
}
private string GenerateStructuredCode(string productCode, InventoryAction action)
{
// Implement GS1 Application Identifiers for enterprise compatibility
var ai = action switch
{
InventoryAction.Receive => "10", // Batch/Lot number
InventoryAction.Ship => "400", // Customer purchase order
InventoryAction.Count => "37", // Quantity
_ => "91" // Internal use
};
return $"({ai}){DateTime.Now:yyMMdd}{productCode}";
}
}對於特殊需求,開發人員可以建立 1-BPP 條碼影像以進行高對比列印,或在現有 PDF 上蓋章條碼。
產生的條碼有哪些自訂選項?
IronBarcode 提供豐富的自訂選項,包括顏色變更、邊距設定以及帶有徽標嵌入的二維碼樣式。






