IRONSOFTWAREHOME

如何使用 .NET MAUI 建立桌面條碼應用程式(掃描器/生成器)

Curtis Chau
Curtis Chau
Updated: 2026年6月29日

對於全面的軟體解決方案,不僅僅是移動可存取性。 能夠在桌面操作系統上原生部署,如 Windows 和 macOS,同樣至關重要。 這種跨平台方法使企業能夠利用工作站的全部功率來處理高容量的任務,如資產追蹤和管理。

如果沒有適當的桌面支援,工作流程會中斷,或者更糟的是,強行轉移到能力較弱的裝置上。 這在庫存管理中特別重要,因為辦公室員工需要生成批次程式碼或快速驗證掃描,而不需離開桌位。

IronBarcode 提供了必要的工具來實現這些功能,確保您的 .NET MAUI 應用程式可以在任何計算機上可靠運行。

在本文中,我們將解釋如何整合 IronBarcode 來構建一個 桌面條碼掃描器 和一個 桌面條碼生成器



.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

桌面條碼掃描器邏輯 CS

接下來,實施使用者點擊按鈕時的邏輯。 在 UI 中的掃描按鈕上附加了一個 OnScanButtonClicked 事件處理程式。

首先使用 PickPhotoAsync 讓使用者選擇要上傳的條碼,然後使用 OpenReadAsync 存取文件流。 圖像資料立即使用 CopyToAsync 複製到 MemoryStream 中。 這允許同時將資料用於在螢幕上顯示圖像以及使用 Read 方法掃描條碼。

最後,如果檢測到有效的條碼,則在 UI 中顯示條碼值;若未在圖像中找到條碼,則顯示紅色訊息。

在測試應用程式前,請將許可金鑰替換為您自己的。

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 &amp; 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

桌面條碼生成器邏輯 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;
            }
        }
    }
}

生成條碼的輸出

生成條碼成功

如您所見,應用程式顯示了生成的條碼並將其儲存到使用者的桌面。

輸出失敗

生成條碼失敗

某些條碼型別對輸入值有特定的限制和格式要求。 條碼生成失敗時,應用程式將顯示如上所示的 IronBarcode 異常。 請根據對應條碼型別的格式,參考詳細的1D2D

要測試上述範例(桌面條碼掃描器桌面條碼生成器),請下載此範例專案。

常見問題

什麼是.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可以用於商業和個人項目,提供靈活的授權選項以適合不同的項目需求。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

準備好開始了嗎?

Nuget Downloads 2,422,100版本:2026.9剛剛發布

立即獲取您的免費30天試用金鑰
不需要信用卡或帳戶建立
C# NuGet程式庫,用於PDF
通過NuGet安裝

版本: 2026.9

PM > Install-Package BarCode
nuget.org/packages/BarCode/
  1. 在解決方案資源管理器中,右鍵點擊References,管理NuGet包
  2. 選擇瀏覽並搜尋"IronBarCode"
  3. 選擇包並安裝
C# PDF DLL
下載DLL

版本: 2026.9

  1. 下載並解壓IronBarCode至您的Solution目錄中的~/Libs等位置
  2. 在Visual Studio解決方案資源管理器中右鍵點擊References,選擇瀏覽,"IronBarCode.dll"

$999起的授權費用

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費即時演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲取您的無義務諮詢
完成下方表單或發送電子郵件至sales@ironsoftware.com
您的詳細資訊將始終保密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立