如何使用 .NET MAUI 建立桌面條碼應用程式(掃描器/產生器)
對於一個全面的軟體解決方案而言,行動存取性並非唯一考慮因素。 能夠在 Windows 和 macOS 等桌面作業系統上進行原生部署的能力同樣至關重要。 這種跨平台方法使企業能夠充分利用工作站的強大功能來處理大量任務,例如資產追蹤和管理。
如果沒有合適的桌面支持,工作流程就會中斷,或者更糟的是,被迫在效能較低的設備上運作。 這在庫存管理中尤其重要,因為辦公室人員需要在不離開辦公桌的情況下快速產生大量代碼或驗證掃描結果。
IronBarcode 提供實現這些功能所需的必要工具,確保您的 .NET MAUI 應用程式在任何電腦上都能可靠地運作。
在本文中,我們將解釋如何整合 IronBarcode 來建立桌面條碼掃描器和桌面條碼產生器。
開始使用 IronBarcode
如何使用 .NET MAUI 在 C# 中建立桌面條碼應用程式
- 下載 IronBarcode C# 庫,以便與 .NET MAUI(桌面平台框架)整合。
- 使用
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><?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事件處理程序。
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;
}
}
}
}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;
}
}
}
}輸出結果包含找到的條碼值

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

如您所見,當使用者上傳不包含條碼的圖片時,會顯示紅色訊息,提示"未找到條碼"。
桌面條碼產生器
下一部分將以相同的概念為基礎,把 IronBarcode 整合到 MAUI 中,建立一個條碼產生器。
條碼產生器介面 XAML
對於生成器的介面,實作了一個簡單的表單,允許透過下拉式選單輸入文字和選擇條碼類型。 包含一個按鈕,用於觸發生成和保存過程,以及一個圖像視圖,用於顯示結果。 請將 MainPage.xaml 檔案替換為以下內容。
請點擊此處查看完整的 1D 條碼列表,點擊此處查看完整的 2D 條碼列表。
<?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>桌面條碼產生器邏輯 CS
接下來,實作按鈕點擊事件的邏輯。 UI 中的產生按鈕附加了一個OnGenerateButtonClicked事件處理程序。
使用者輸入經過驗證,以確保文字存在並且已選擇類型,之後將選擇對應到正確的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;
}
}
}
}輸出產生的條碼

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

某些條碼類型對輸入值有限制和格式要求。 當條碼產生失敗時,應用程式會顯示 IronBarcode 異常,如上圖所示。 請參考對應的詳細一維和二維條碼格式說明,以了解每種條碼類型的格式要求。
若要測試上述範例(桌面條碼掃描器和桌面條碼產生器),請下載此範例專案。
常見問題解答
.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 可用於商業和個人項目,提供靈活的授權選項以滿足不同的專案需求。






