如何使用 .NET MAUI 建立桌面 BarCode 應用程式(掃描器/生成器)
要打造一套全面的軟體解決方案,不僅僅是關於行動裝置的無障礙存取。 能夠原生部署於 Windows 和 macOS 等桌面作業系統上,同樣至關重要。 這種跨平台方法使企業能夠充分利用工作站的強大效能,處理資產追蹤與管理等高負載任務。
若缺乏適當的桌面端支援,工作流程將受到中斷,甚至更糟的是被迫轉移至功能較弱的裝置上。 這在庫存管理領域尤為重要,因為辦公室人員需要在不離開座位的情況下,快速生成批次代碼或驗證掃描結果。
IronBarcode 提供實現這些功能所需的工具,確保您的 .NET MAUI 應用程式能在任何電腦上穩定運行。
本文將說明如何整合 IronBarcode,以建置桌面 BarCode 掃描器與桌面 BarCode 產生器。
如何使用 C# 和 .NET MAUI 建立桌面 BarCode 應用程式
- 下載 IronBarcode C# 程式庫,以整合至 .NET MAUI(桌面平台框架)
- 使用
Read讀取使用者上傳的 BARCODE - 將 BARCODE 值顯示於 .NET MAUI 使用者介面
- 使用
CreateBarcode根據字串值產生 BARCODE - 在 .NET MAUI 介面中顯示生成的 BarCode,並將其儲存為圖片
.NET MAUI 桌面應用程式
將 IronBarcode 整合至 .NET MAUI 應用程式非常簡單,因為該程式庫開箱即用,可原生支援桌面平台。 在此範例中,我們將分別使用 IronBarcode 建立條碼掃描器與條碼產生器。
我們先從BarCode掃描器開始。
BarCode掃描器介面 XAML
針對 .NET MAUI 介面,已實作一個簡易介面,讓使用者能透過提交按鈕上傳 BARCODE 圖片。 專案中的 MainPage.xaml 檔案應替換為以下內容。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage"
BackgroundColor="{DynamicResource PageBackgroundColor}">
<ScrollView>
<VerticalStackLayout Spacing="25" Padding="30" VerticalOptions="Center">
<Label Text="Desktop Barcode Scanner"
FontSize="32"
HorizontalOptions="Center" />
<Image x:Name="ScannerImage"
HeightRequest="300"
WidthRequest="400"
BackgroundColor="#F0F0F0"
Aspect="AspectFit"
HorizontalOptions="Center" />
<Button Text="Select Image to Scan"
Clicked="OnScanButtonClicked"
HorizontalOptions="Center"
WidthRequest="200"/>
<Label x:Name="ResultLabel"
Text="Result will appear here..."
FontSize="20"
HorizontalOptions="Center"
HorizontalTextAlignment="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage"
BackgroundColor="{DynamicResource PageBackgroundColor}">
<ScrollView>
<VerticalStackLayout Spacing="25" Padding="30" VerticalOptions="Center">
<Label Text="Desktop Barcode Scanner"
FontSize="32"
HorizontalOptions="Center" />
<Image x:Name="ScannerImage"
HeightRequest="300"
WidthRequest="400"
BackgroundColor="#F0F0F0"
Aspect="AspectFit"
HorizontalOptions="Center" />
<Button Text="Select Image to Scan"
Clicked="OnScanButtonClicked"
HorizontalOptions="Center"
WidthRequest="200"/>
<Label x:Name="ResultLabel"
Text="Result will appear here..."
FontSize="20"
HorizontalOptions="Center"
HorizontalTextAlignment="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
桌面BarCode掃描器邏輯 CS
接下來,將實作使用者點擊按鈕時的邏輯。 UI 中的掃描按鈕已附加一個 OnScanButtonClicked 事件處理常式。
首先使用 PickPhotoAsync 讓使用者選擇要上傳的BARCODE,接著使用 OpenReadAsync 存取檔案串流。 圖像資料會立即透過 CopyToAsync 複製到 MemoryStream 中。 這使得資料既能用於在螢幕上顯示圖像,又能供 Read 方法掃描 BARCODE。
最後,若偵測到有效BarCode,系統將在使用者介面中顯示BarCode值;若未在圖片中找到BarCode,則會顯示紅色訊息提示。
using IronBarCode;
namespace MauiApp1
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
// Your license key is set here
IronBarCode.License.LicenseKey = "YOUR_KEY"
}
private async void OnScanButtonClicked(object sender, EventArgs e)
{
try
{
var fileResult = await MediaPicker.Default.PickPhotoAsync();
if (fileResult != null)
{
// 1. Copy the file content into a byte array or MemoryStream immediately
// This ensures we have the data in memory before the file closes
byte[] imageBytes;
using (var stream = await fileResult.OpenReadAsync())
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
imageBytes = memoryStream.ToArray();
}
// 2. Set the Image Source for the UI
// We give the UI a FRESH stream from the bytes we just saved
ScannerImage.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
// 3. Process the Barcode
// We give IronBarcode its OWN fresh stream from the same bytes
using (var processingStream = new MemoryStream(imageBytes))
{
// 4. Read the barcode with Read
var results = BarcodeReader.Read(processingStream);
// 5. Display barcode results
if (results != null && results.Count > 0)
{
// Successfully found barcode value
ResultLabel.Text = $"Success: {results[0].Value}";
ResultLabel.TextColor = Colors.Green;
}
else
{
// Image uploaded has no barcode or barcode value is not found
ResultLabel.Text = "No barcode detected.";
ResultLabel.TextColor = Colors.Red;
}
}
}
}
catch (Exception ex)
{
// Display any exception thrown in runtime
ResultLabel.Text = $"Error: {ex.Message}";
ResultLabel.TextColor = Colors.Red;
}
}
}
}
using IronBarCode;
namespace MauiApp1
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
// Your license key is set here
IronBarCode.License.LicenseKey = "YOUR_KEY"
}
private async void OnScanButtonClicked(object sender, EventArgs e)
{
try
{
var fileResult = await MediaPicker.Default.PickPhotoAsync();
if (fileResult != null)
{
// 1. Copy the file content into a byte array or MemoryStream immediately
// This ensures we have the data in memory before the file closes
byte[] imageBytes;
using (var stream = await fileResult.OpenReadAsync())
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
imageBytes = memoryStream.ToArray();
}
// 2. Set the Image Source for the UI
// We give the UI a FRESH stream from the bytes we just saved
ScannerImage.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
// 3. Process the Barcode
// We give IronBarcode its OWN fresh stream from the same bytes
using (var processingStream = new MemoryStream(imageBytes))
{
// 4. Read the barcode with Read
var results = BarcodeReader.Read(processingStream);
// 5. Display barcode results
if (results != null && results.Count > 0)
{
// Successfully found barcode value
ResultLabel.Text = $"Success: {results[0].Value}";
ResultLabel.TextColor = Colors.Green;
}
else
{
// Image uploaded has no barcode or barcode value is not found
ResultLabel.Text = "No barcode detected.";
ResultLabel.TextColor = Colors.Red;
}
}
}
}
catch (Exception ex)
{
// Display any exception thrown in runtime
ResultLabel.Text = $"Error: {ex.Message}";
ResultLabel.TextColor = Colors.Red;
}
}
}
}
Imports IronBarCode
Namespace MauiApp1
Partial Public Class MainPage
Inherits ContentPage
Public Sub New()
InitializeComponent()
' Your license key is set here
IronBarCode.License.LicenseKey = "YOUR_KEY"
End Sub
Private Async Sub OnScanButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim fileResult = Await MediaPicker.Default.PickPhotoAsync()
If fileResult IsNot Nothing Then
' 1. Copy the file content into a byte array or MemoryStream immediately
' This ensures we have the data in memory before the file closes
Dim imageBytes As Byte()
Using stream = Await fileResult.OpenReadAsync(), memoryStream = New MemoryStream()
Await stream.CopyToAsync(memoryStream)
imageBytes = memoryStream.ToArray()
End Using
' 2. Set the Image Source for the UI
' We give the UI a FRESH stream from the bytes we just saved
ScannerImage.Source = ImageSource.FromStream(Function() New MemoryStream(imageBytes))
' 3. Process the Barcode
' We give IronBarcode its OWN fresh stream from the same bytes
Using processingStream = New MemoryStream(imageBytes)
' 4. Read the barcode with Read
Dim results = BarcodeReader.Read(processingStream)
' 5. Display barcode results
If results IsNot Nothing AndAlso results.Count > 0 Then
' Successfully found barcode value
ResultLabel.Text = $"Success: {results(0).Value}"
ResultLabel.TextColor = Colors.Green
Else
' Image uploaded has no barcode or barcode value is not found
ResultLabel.Text = "No barcode detected."
ResultLabel.TextColor = Colors.Red
End If
End Using
End If
Catch ex As Exception
' Display any exception thrown in runtime
ResultLabel.Text = $"Error: {ex.Message}"
ResultLabel.TextColor = Colors.Red
End Try
End Sub
End Class
End Namespace
輸出結果:已找到BarCode值
如您所見,應用程式會顯示BARCODE掃描結果以及上傳的BARCODE圖片。
輸出結果:未找到BarCode值
如您所見,當使用者上傳不包含BARCODE的圖片時,系統會顯示紅色提示訊息:"未找到BARCODE。"
桌面BarCode生成器
下一部分將延續此概念,透過將 IronBarcode 整合至 MAUI,打造一個 BARCODE 產生器。
BarCode 產生器介面 XAML
針對生成器的介面,已實作一個簡單的表單,可透過下拉式選單輸入文字並選擇BarCode類型。 系統包含一個按鈕,用於觸發生成與節省流程,並附有圖片檢視窗格以顯示結果。 請將 MainPage.xaml 檔案替換為以下內容。
請參閱此處以查看一維BARCODE的完整清單,以及此處以查看二維BARCODE。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage"
BackgroundColor="{DynamicResource PageBackgroundColor}">
<ScrollView>
<VerticalStackLayout Spacing="20" Padding="30" VerticalOptions="Center">
<Label Text="Barcode Generator"
FontSize="32"
HorizontalOptions="Center" />
<Entry x:Name="BarcodeEntry"
Placeholder="Enter value (e.g. 12345 or https://ironsoftware.com)"
WidthRequest="300" />
<Picker x:Name="BarcodeTypePicker"
Title="Select Barcode Type"
WidthRequest="300">
<Picker.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>QRCode</x:String>
<x:String>Code128</x:String>
<x:String>EAN13</x:String>
<x:String>Code39</x:String>
<x:String>PDF417</x:String>
</x:Array>
</Picker.ItemsSource>
</Picker>
<Button Text="Generate & Save"
Clicked="OnGenerateButtonClicked"
HorizontalOptions="Center"
WidthRequest="200" />
<Image x:Name="GeneratedImage"
HeightRequest="200"
WidthRequest="300"
BackgroundColor="#F0F0F0"
Aspect="AspectFit" />
<Label x:Name="StatusLabel"
FontSize="16"
HorizontalOptions="Center"
HorizontalTextAlignment="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage"
BackgroundColor="{DynamicResource PageBackgroundColor}">
<ScrollView>
<VerticalStackLayout Spacing="20" Padding="30" VerticalOptions="Center">
<Label Text="Barcode Generator"
FontSize="32"
HorizontalOptions="Center" />
<Entry x:Name="BarcodeEntry"
Placeholder="Enter value (e.g. 12345 or https://ironsoftware.com)"
WidthRequest="300" />
<Picker x:Name="BarcodeTypePicker"
Title="Select Barcode Type"
WidthRequest="300">
<Picker.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>QRCode</x:String>
<x:String>Code128</x:String>
<x:String>EAN13</x:String>
<x:String>Code39</x:String>
<x:String>PDF417</x:String>
</x:Array>
</Picker.ItemsSource>
</Picker>
<Button Text="Generate & Save"
Clicked="OnGenerateButtonClicked"
HorizontalOptions="Center"
WidthRequest="200" />
<Image x:Name="GeneratedImage"
HeightRequest="200"
WidthRequest="300"
BackgroundColor="#F0F0F0"
Aspect="AspectFit" />
<Label x:Name="StatusLabel"
FontSize="16"
HorizontalOptions="Center"
HorizontalTextAlignment="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
桌面BarCode產生器 Logic CS
接下來,將實作按鈕點擊事件的邏輯。 UI 中的"產生"按鈕已附加一個 OnGenerateButtonClicked 事件處理常式。
系統會驗證使用者輸入,以確保文字存在且已選取類型,之後將選取內容映射至正確的 BarcodeEncoding。 BarcodeWriter.CreateBarcode 用於生成圖片、調整其大小,並將其轉換為 JPEG 二進位資料。 該圖像隨後會透過 MemoryStream 顯示於螢幕上。
最後,生成的 BARCODE 檔案會透過 File.WriteAllBytes 直接儲存至使用者的桌面,並更新狀態標籤以確認儲存位置。
using IronBarCode;
using System.IO; // Required for saving files
namespace MauiApp1
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
IronBarCode.License.LicenseKey = "YOUR-KEY";
// Set default selection
BarcodeTypePicker.SelectedIndex = 0;
}
private void OnGenerateButtonClicked(object sender, EventArgs e)
{
try
{
// 1. Get and Validate Input
string text = BarcodeEntry.Text;
if (string.IsNullOrWhiteSpace(text))
{
StatusLabel.Text = "Error: Please enter text.";
StatusLabel.TextColor = Colors.Red;
return;
}
if (BarcodeTypePicker.SelectedIndex == -1)
{
StatusLabel.Text = "Error: Please select a type.";
StatusLabel.TextColor = Colors.Red;
return;
}
// 2. Determine Encoding Type
string selectedType = BarcodeTypePicker.SelectedItem.ToString();
BarcodeEncoding encoding = BarcodeEncoding.QRCode;
switch (selectedType)
{
case "QRCode": encoding = BarcodeEncoding.QRCode; break;
case "Code128": encoding = BarcodeEncoding.Code128; break;
case "EAN13": encoding = BarcodeEncoding.EAN13; break;
case "Code39": encoding = BarcodeEncoding.Code39; break;
case "PDF417": encoding = BarcodeEncoding.PDF417; break;
}
// 3. Generate Barcode
var barcode = BarcodeWriter.CreateBarcode(text, encoding);
barcode.ResizeTo(400, 200); // Optional resizing
// 4. Convert to Bytes (JPEG)
var bytes = barcode.ToJpegBinaryData();
// 5. Update UI
GeneratedImage.Source = ImageSource.FromStream(() => new MemoryStream(bytes));
// 6. Save to Desktop automatically
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fileName = $"barcode_{DateTime.Now:yyyyMMdd_HHmmss}.jpg";
string fullPath = Path.Combine(desktopPath, fileName);
File.WriteAllBytes(fullPath, bytes);
// 7. Show Success Message
StatusLabel.Text = $"Saved to Desktop:\n{fileName}";
StatusLabel.TextColor = Colors.Green;
}
catch (Exception ex)
{
StatusLabel.Text = $"Error: {ex.Message}";
StatusLabel.TextColor = Colors.Red;
}
}
}
}
using IronBarCode;
using System.IO; // Required for saving files
namespace MauiApp1
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
IronBarCode.License.LicenseKey = "YOUR-KEY";
// Set default selection
BarcodeTypePicker.SelectedIndex = 0;
}
private void OnGenerateButtonClicked(object sender, EventArgs e)
{
try
{
// 1. Get and Validate Input
string text = BarcodeEntry.Text;
if (string.IsNullOrWhiteSpace(text))
{
StatusLabel.Text = "Error: Please enter text.";
StatusLabel.TextColor = Colors.Red;
return;
}
if (BarcodeTypePicker.SelectedIndex == -1)
{
StatusLabel.Text = "Error: Please select a type.";
StatusLabel.TextColor = Colors.Red;
return;
}
// 2. Determine Encoding Type
string selectedType = BarcodeTypePicker.SelectedItem.ToString();
BarcodeEncoding encoding = BarcodeEncoding.QRCode;
switch (selectedType)
{
case "QRCode": encoding = BarcodeEncoding.QRCode; break;
case "Code128": encoding = BarcodeEncoding.Code128; break;
case "EAN13": encoding = BarcodeEncoding.EAN13; break;
case "Code39": encoding = BarcodeEncoding.Code39; break;
case "PDF417": encoding = BarcodeEncoding.PDF417; break;
}
// 3. Generate Barcode
var barcode = BarcodeWriter.CreateBarcode(text, encoding);
barcode.ResizeTo(400, 200); // Optional resizing
// 4. Convert to Bytes (JPEG)
var bytes = barcode.ToJpegBinaryData();
// 5. Update UI
GeneratedImage.Source = ImageSource.FromStream(() => new MemoryStream(bytes));
// 6. Save to Desktop automatically
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fileName = $"barcode_{DateTime.Now:yyyyMMdd_HHmmss}.jpg";
string fullPath = Path.Combine(desktopPath, fileName);
File.WriteAllBytes(fullPath, bytes);
// 7. Show Success Message
StatusLabel.Text = $"Saved to Desktop:\n{fileName}";
StatusLabel.TextColor = Colors.Green;
}
catch (Exception ex)
{
StatusLabel.Text = $"Error: {ex.Message}";
StatusLabel.TextColor = Colors.Red;
}
}
}
}
Imports IronBarCode
Imports System.IO ' Required for saving files
Namespace MauiApp1
Public Partial Class MainPage
Inherits ContentPage
Public Sub New()
InitializeComponent()
IronBarCode.License.LicenseKey = "YOUR-KEY"
' Set default selection
BarcodeTypePicker.SelectedIndex = 0
End Sub
Private Sub OnGenerateButtonClicked(sender As Object, e As EventArgs)
Try
' 1. Get and Validate Input
Dim text As String = BarcodeEntry.Text
If String.IsNullOrWhiteSpace(text) Then
StatusLabel.Text = "Error: Please enter text."
StatusLabel.TextColor = Colors.Red
Return
End If
If BarcodeTypePicker.SelectedIndex = -1 Then
StatusLabel.Text = "Error: Please select a type."
StatusLabel.TextColor = Colors.Red
Return
End If
' 2. Determine Encoding Type
Dim selectedType As String = BarcodeTypePicker.SelectedItem.ToString()
Dim encoding As BarcodeEncoding = BarcodeEncoding.QRCode
Select Case selectedType
Case "QRCode"
encoding = BarcodeEncoding.QRCode
Case "Code128"
encoding = BarcodeEncoding.Code128
Case "EAN13"
encoding = BarcodeEncoding.EAN13
Case "Code39"
encoding = BarcodeEncoding.Code39
Case "PDF417"
encoding = BarcodeEncoding.PDF417
End Select
' 3. Generate Barcode
Dim barcode = BarcodeWriter.CreateBarcode(text, encoding)
barcode.ResizeTo(400, 200) ' Optional resizing
' 4. Convert to Bytes (JPEG)
Dim bytes = barcode.ToJpegBinaryData()
' 5. Update UI
GeneratedImage.Source = ImageSource.FromStream(Function() New MemoryStream(bytes))
' 6. Save to Desktop automatically
Dim desktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim fileName As String = $"barcode_{DateTime.Now:yyyyMMdd_HHmmss}.jpg"
Dim fullPath As String = Path.Combine(desktopPath, fileName)
File.WriteAllBytes(fullPath, bytes)
' 7. Show Success Message
StatusLabel.Text = $"Saved to Desktop:{Environment.NewLine}{fileName}"
StatusLabel.TextColor = Colors.Green
Catch ex As Exception
StatusLabel.Text = $"Error: {ex.Message}"
StatusLabel.TextColor = Colors.Red
End Try
End Sub
End Class
End Namespace
帶有生成BarCode的輸出
如您所見,此應用程式會顯示生成的BARCODE,並將其儲存至使用者的桌面。
輸出失敗
某些BarCode類型對輸入值有特定限制與格式要求。 當 BarCode 生成失敗時,應用程式會顯示如上所示的 IronBarcode 例外狀況。 請參閱各 BarCode 類型的詳細說明,了解 1D 和 2D BarCode 的格式規範。
若要測試上述範例(桌面BarCode掃描器與桌面BarCode產生器),請下載此範例專案。
常見問題
什麼是.NET MAUI?
.NET MAUI是一個跨平台框架,用於使用C#和XAML創建原生移動和桌面應用程式。它允許開發人員使用單一程式碼庫為Android、iOS、macOS和Windows構建應用程式。
如何在.NET MAUI應用程式中使用IronBarcode?
IronBarcode可以集成到.NET MAUI應用程式中,以啟用條碼生成和掃描功能。它提供了在多個桌面平台間創建和讀取條碼的簡單方法。
IronBarcode可以生成哪些類型的條碼?
IronBarcode支援生成多種條碼格式,包括QR碼、Code 128、Code 39、UPC、EAN等,使其可適應任何桌面應用程式的需求。
是否可以使用IronBarcode構建的桌面應用程式掃描條碼?
是的,IronBarcode可以用於掃描桌面應用程式中的條碼,使使用者能夠通過應用程式介面快速而高效地解碼條碼信息。
使用IronBarcode進行條碼應用程式的優勢有哪些?
IronBarcode提供高精準度、速度和易用性。它可無縫整合到.NET MAUI中,為桌面應用程式提供全面的條碼生成和掃描支援。
IronBarcode能夠處理大量的條碼數據嗎?
是的,IronBarcode專為高效地處理大量條碼數據而設計,使其適用於需要處理大量條碼任務的應用程式。
我需要單獨的程式庫來進行條碼掃描和生成嗎?
不需要,IronBarcode在單一程式庫中提供條碼掃描和生成功能,簡化了桌面應用程式的開發過程。
使用IronBarcode和.NET MAUI的系統需求是什麼?
IronBarcode需要與.NET MAUI相容的.NET環境。它支援Windows、macOS和其他.NET MAUI應用程式可以運行的平台。
IronBarcode如何確保條碼準確性?
IronBarcode使用先進的算法,確保條碼生成和掃描的高精準度,減少編碼或解碼條碼數據時出錯的可能性。
IronBarcode可以用於商業和個人專案嗎?
是的,IronBarcode可以用於商業和個人專案,提供靈活的授權選項以滿足不同專案的需求。

