How to Create a Desktop BarCode Application (Scanner/Generator) with .NET MAUI

This article was translated from English: Does it need improvement?
Translated
View the article in English

包括的なソフトウェア・ソリューションでは、モバイル・アクセシビリティだけではありません。 WindowsやmacOSなどのデスクトップOSにネイティブにデプロイできることも重要です。 このクロスプラットフォームアプローチにより、企業は資産追跡や管理などの大量タスクにワークステーションの能力をフルに活用することができます。

適切なデスクトップサポートがないと、ワークフローが中断されたり、最悪の場合、性能の低いデバイスを使わざるを得なくなったりします。 これは、オフィススタッフがデスクを離れることなくコードのバッチを生成したり、スキャンを迅速に確認したりする必要がある在庫管理では特に重要です。

IronBarcodeは、これらの機能を実装するために必要なツールを提供し、.NET MAUIアプリケーションがどのコンピュータでも確実に動作することを保証します。

この記事では、デスクトップBarCodeスキャナデスクトップBarCodeジェネレータの両方を構築するためにIronBarcodeを統合する方法を説明します。



.NET MAUIデスクトップアプリケーション

IronBarcodeを.NET MAUIアプリに統合することは、ライブラリがすぐにデスクトッププラットフォームでネイティブに動作するため、簡単です。 この例では、IronBarcodeを使用してバーコードスキャナとバーコードジェネレータの両方を別々に作成します。

まず、バーコードスキャナから始めましょう。

バーコード スキャナー インターフェース 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>
XML

デスクトップ バーコード スキャナー Logic 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;
            }
        }
    }
}
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;
            }
        }
    }
}
$vbLabelText   $csharpLabel

バーコードの値が見つかったときの出力

出力された BarCode

ご覧のように、アプリケーションはバーコードの結果とアップロードされたバーコード画像を表示します。

バーコードの値が見つかりませんと出力されます

出力された BarCode は見つかりませんでした。

ご覧のように、ユーザーがバーコードを含まない画像をアップロードすると、"No barcodes found "という赤いメッセージが表示されます。

デスクトップ バーコード ジェネレーター

次のパートでは、IronBarcodeをMAUIに統合してバーコードジェネレーターを作成することで、同じコンセプトを構築します。

バーコード ジェネレーター インターフェース XAML

ジェネレーターのインターフェースには、テキスト入力とドロップダウンメニューによるバーコードタイプの選択を可能にするシンプルなフォームが実装されています。 生成と保存のプロセスを開始するためのボタンと、結果を表示するための画像ビューが含まれています。 MainPage.xamlファイルは、以下に示す内容に置き換えてください。

1次元バーコードの完全なリストについてはこちらを、2次元バーコードについてはこちらを参照してください。

<?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>
XML

デスクトップ バーコード ジェネレーター Logic 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;
            }
        }
    }
}
$vbLabelText   $csharpLabel

生成された BarCode で出力する

バーコード生成の成功

ご覧のように、アプリケーションは生成されたBarCodeを表示し、ユーザーのデスクトップに保存します。

出力の失敗

バーコードの失敗を生成する

バーコードの種類によっては、入力値に制限や形式要件があります。 バーコードの生成に失敗すると、アプリケーションは上記のようにIronBarcode例外を表示します。 各バーコードタイプのフォーマットについては、それぞれの詳細1D2Dを参照してください。

上記の例(デスクトップ・バーコード・スキャナデスクトップ・バーコード・ジェネレータ)をテストするには、このサンプル・プロジェクトをダウンロードしてください。

よくある質問

.NET MAUIとは?

.NET MAUIは、C#とXAMLを使用してネイティブのモバイルアプリとデスクトップアプリを作成するためのクロスプラットフォームフレームワークです。開発者は、単一のコードベースを使用して、Android、iOS、macOS、Windows用のアプリケーションを構築できます。

IronBarcode .NET MAUIアプリケーションでどのように使用できますか?

IronBarcodeを.NET MAUIアプリケーションに統合することで、バーコードの生成とスキャンが可能になります。IronBarcodeは、複数のデスクトップ・プラットフォームでバーコードを作成し、読み取る簡単な方法を提供します。

IronBarcode はどのような種類のバーコードを生成できますか?

IronBarcodeはQRコード、Code 128、Code 39、UPC、EANなど様々なバーコードフォーマットの生成をサポートしており、デスクトップアプリケーションのニーズに対応します。

IronBarcodeで構築されたデスクトップアプリケーションを使ってバーコードをスキャンすることは可能ですか?

IronBarcodeはデスクトップアプリケーションのバーコードスキャンに使用でき、ユーザーはアプリケーションのインターフェイスから素早く効率的にバーコード情報をデコードすることができます。

バーコードアプリケーションにIronBarcodeを使用する利点は何ですか?

IronBarcodeは、高い精度、スピード、使いやすさを提供します。.NET MAUIとシームレスに統合され、デスクトップアプリケーションでのバーコード生成とスキャンを包括的にサポートします。

IronBarcodeは大量のバーコードデータを処理できますか?

IronBarcodeは大量のバーコードデータを効率的に処理するように設計されており、広範なバーコード処理を必要とするアプリケーションに適しています。

バーコードのスキャンと生成には、別のライブラリが必要ですか?

IronBarcodeは、バーコードのスキャンと生成の両方の機能を単一のライブラリで提供し、デスクトップアプリケーションの開発プロセスを簡素化します。

.NET MAUIでIronBarcodeを使用するためのシステム要件は何ですか?

IronBarcodeは、.NET MAUIと互換性のある.NET環境を必要とします。Windows、macOS、その他.NET MAUIアプリケーションが動作するプラットフォームをサポートしています。

IronBarcodeはどのようにバーコードの精度を保証していますか?

IronBarcodeは高度なアルゴリズムを使用し、バーコードの生成とスキャンの両方で高い精度を保証し、バーコードデータのエンコードやデコードにおけるエラーの可能性を低減します。

IronBarcodeは商用でも個人プロジェクトでも使用できますか?

また、IronBarcodeは商用、個人プロジェクトともに使用可能で、さまざまなプロジェクト要件に合わせた柔軟なライセンスオプションを提供しています。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

準備はできましたか?
Nuget ダウンロード 2,121,847 | バージョン: 2026.3 リリース
Still Scrolling Icon

まだスクロールしていますか?

すぐに証拠が欲しいですか? PM > Install-Package BarCode
サンプルを実行する 文字列が BarCode になるのを見る。