如何使用 .NET MAUI 创建桌面条形码应用程序(扫描器/生成器)

Curtis Chau
Curtis Chau
更新: 2026年7月21日

对于一个全面的软件解决方案而言,移动访问性并非唯一考量因素。 能够在 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

接下来,实现用户点击按钮时的逻辑。 一个 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;
            }
        }
    }
}

输出结果包含找到的条形码值

找到的条形码输出

如您所见,该应用程序显示了条形码结果和上传的条形码图像。

未找到条形码值

未找到条形码输出

如您所见,当用户上传不包含条形码的图片时,会显示一条红色消息,提示“未找到条形码”。

桌面条码生成器

下一部分将以相同的概念为基础,把 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

接下来,实现按钮点击事件的逻辑。 一个 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;
            }
        }
    }
}

输出生成的条形码

条形码生成成功

如您所见,该应用程序会显示生成的条形码并将其保存到用户的桌面。

输出失败

条形码故障生成

某些条形码类型对输入值有限制和格式要求。 当条形码生成失败时,应用程序会显示 IronBarcode 异常,如上所示。 请参考各自详细的 1D 和 2D 格式以获取每种条形码类型的格式。

要测试上述示例(桌面条形码扫描仪和桌面条形码生成器),请 下载 此示例项目。

常见问题

将IronBarcode集成到.NET MAUI桌面应用程序中的目的是什么?

将IronBarcode集成到.NET MAUI应用程序中使开发人员能够构建一个跨平台条码扫描和生成解决方案,可以直接在Windows和macOS等桌面环境中运行,从而增强库存管理和资产跟踪等工作流程。

如何在.NET MAUI中使用IronBarcode实现桌面条码扫描器?

要实现条码扫描器,使用IronBarcode的Read方法扫描用户上传的条码图像,并在.NET MAUI UI中显示结果。這涉及处理用户输入、处理条码数据以及使用扫描结果更新界面。

如何使用IronBarcode创建桌面条码生成器?

可以在.NET MAUI中使用IronBarcode创建一个桌面条码生成器,通过提供文本输入和条码类型选择的UI。然后,使用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。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

阅读更多

准备开始了吗?

NuGet 下载量 2,575,633版本:2026.11刚刚发布