如何使用 .NET MAUI 建立桌面條碼應用程式(掃描器/產生器)
對於一個全面的軟體解決方案而言,行動存取性並非唯一考慮因素。 能夠在 Windows 和 macOS 等桌面作業系統上進行原生部署的能力同樣至關重要。 這種跨平台方法使企業能夠充分利用工作站的強大功能來處理大量任務,例如資產追蹤和管理。
如果沒有合適的桌面支援,工作流程就會中斷,或者更糟的是,被迫在效能較低的設備上運作。 這在庫存管理中尤其重要,因為辦公室人員需要在不離開辦公桌的情況下快速產生大量代碼或驗證掃描結果。
IronBarcode 提供實現這些功能所需的必要工具,確保您的 .NET MAUI 應用程式在任何電腦上都能可靠地運作。
在本文中,我們將解釋如何整合 IronBarcode 來建立桌面條碼掃描器和桌面條碼產生器。
如何使用 .NET MAUI 在 C# 中建立桌面條碼應用程式
- 下載IronBarcode C#程式庫以整合.NET MAUI (Desktop Platform Framework)
- 使用
Read來讀取使用者提供的已上傳條碼 - 在 .NET MAUI 使用者介面中顯示條碼值
- 使用
CreateBarcode產生帶有字串值的條碼 - 在 .NET MAUI 使用者介面中顯示生成的條碼並將其儲存為圖像
.NET MAUI 桌面應用程式
將 IronBarcode 整合到 .NET MAUI 應用程式中非常簡單,因為該程式庫開箱即用,可與桌面平台原生相容。 在這個範例中,我們將分別使用 IronBarcode 來建立條碼掃描器和條碼產生器。
我們先從條碼掃描器開始。
條碼掃描器介面 XAML
對於 .NET MAUI 接口,實現了一個簡單的接口,允許用戶透過提交按鈕上傳條碼圖像。 項目中的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>
桌面條碼掃描器邏輯 CS
接下來,實作使用者點擊按鈕時的邏輯。 一個OnScanButtonClicked事件處理器已附加在UI的掃描按鈕上。
PickPhotoAsync 首次使用讓用戶選擇要上傳的條碼,隨後使用OpenReadAsync訪問文件流。 圖像數據會立即使用CopyToAsync複製到MemoryStream中。 這允許數據同時用於在螢幕上顯示影像以及供Read方法掃描條碼。
最後,如果偵測到有效的條碼,則會在使用者介面中顯示條碼值;如果未在影像中找到條碼,則會顯示紅色訊息。
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
Public Partial 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(sender As Object, 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 NamespaceImports IronBarCode
Namespace MauiApp1
Public Partial 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(sender As Object, 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輸出結果包含找到的條碼值

如您所見,該應用程式顯示了條碼結果和上傳的條碼圖像。
未找到條碼值

如您所見,當使用者上傳不包含條碼的圖片時,會顯示紅色訊息,提示「未找到條碼」。
桌面條碼產生器
下一部分將以相同的概念為基礎,把 IronBarcode 整合到 MAUI 中,建立一個條碼產生器。
條碼產生器介面 XAML
對於生成器的介面,實作了一個簡單的表單,允許透過下拉式選單輸入文字和選擇條碼類型。 包含一個按鈕,用於觸發生成和保存過程,以及一個圖像視圖,用於顯示結果。 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="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>
桌面條碼產生器邏輯 CS
接下來,實作按鈕點擊事件的邏輯。 一個OnGenerateButtonClicked事件處理器已附加在UI的生成按鈕上。
會驗證使用者輸入以確保文字存在並選擇了一種類型,然後將選擇映射到正確的BarcodeEncoding。 使用BarcodeWriter.CreateBarcode生成影像、調整大小,並轉換為JPEG二進制數據。 然後使用MemoryStream在螢幕上顯示影像。
最後,使用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 NamespaceImports 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輸出產生的條碼

如您所見,該應用程式會顯示產生的條碼並將其儲存到使用者的桌面。
輸出失敗

某些條碼類型對輸入值有限制和格式要求。 當條碼產生失敗時,應用程式會顯示 IronBarcode 異常,如上圖所示。 請參考各條碼類型的格式化詳細資訊,請參考1D和2D。
要測試上述範例(桌面條碼掃描器和桌面條碼生成器),請下載此範例專案。
常見問題
將IronBarcode整合到.NET MAUI桌面應用程式中的目的為何?
整合IronBarcode到.NET MAUI應用程式中,能使開發者構建可直接在Windows和macOS等桌面環境中運行的跨平台條碼掃描和生成解決方案,來加強如庫存管理及資產追蹤等工作流程。
如何在.NET MAUI中使用IronBarcode實現桌面條碼掃描器?
要實現條碼掃描器,可使用IronBarcode的Read方法來掃描用戶上傳的條碼影像,並在.NET MAUI UI上顯示結果。這涉及處理用戶輸入、處理條碼數據,並用掃描結果更新介面。
如何使用IronBarcode創建桌面條碼生成器?
可以在.NET MAUI中使用IronBarcode創建桌面條碼生成器,提供用於文本輸入和條碼類型選擇的使用者介面。然後使用BarcodeWriter.CreateBarcode方法生成條碼影像,顯示並將其保存到用戶的桌面。
IronBarcode生成器支持保存哪些格式的條碼影像?
IronBarcode支持將條碼影像保存為多種格式,包括JPEG。範例實現將生成的條碼影像保存為JPEG文件。
IronBarcode能否在桌面應用程式中處理不同類型的條碼?
是的,IronBarcode可以處理多種條碼類型,如QRCode、Code128、EAN13、Code39和PDF417,允許在桌面應用程式中創建和閱讀不同的條碼格式,提供靈活性。
在條碼掃描器的邏輯中`OnScanButtonClicked`的作用是什麼?
OnScanButtonClicked是當用戶點擊掃描按鈕時觸發的事件處理器。它管理選擇、閱讀和顯示條碼影像的過程,使用IronBarcode在.NET MAUI UI中完成。
為什麼跨平台功能對於桌面條碼應用程式很重要?
跨平台功能可確保條碼應用程式能夠在多種桌面操作系統上自然運行,例如Windows和macOS,使企業能夠使用功能強大的工作站來管理例如資產追蹤和庫存管理等任務。
IronBarcode如何在條碼應用程式上下文中提高工作效率?
IronBarcode通過允許在桌面環境中直接進行條碼生成和掃描,提升了工作效率,減少了對移動設備的依賴,從而減少了中斷並提高了例如批量代碼生成和辦公室設置中的掃描驗證等工作的速度。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。