C# QR コード ジェネレーター アプリケーション

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

C#を使用してQRコードを作成するためのガイドへようこそ! QRコードと.NETバーコードDLLは、情報を迅速かつ効率的に共有するための人気のある手段になっています。 アプリを開発する場合でも、ウェブサイトを管理する場合でも、リンクを共有するためのきちんとした方法を探している場合でも、これらのコードは非常に便利です。 このガイドでは、 IronQRを使用して QR コードを効率的に生成し、ニーズに合わせた QR コードを生成できるようにする方法を説明します。 このライブラリを使用すると、複雑なロジックに入り込むことなく、C#を使用してQRコードを作成することができます。 手順を案内し、始めるために必要なすべてのものを用意します。 アプリにQRコード生成機能を追加したい場合でも、その方法に興味がある場合でも、正しい場所にいます。 始めましょう。

C# で QR コード ジェネレーター ライブラリをインストールする

今日あなたのプロジェクトでIronQRを無料トライアルで使用開始。

最初のステップ:
green arrow pointer


始める前に、 IronQR NuGet パッケージをインストールする必要があります。

Install-Package IronQR

IronQR: C# QR ライブラリ

IronQRは、.NETアプリケーションにQRコード機能を統合するためのC# QRコードライブラリです。 IronQRは、C#、VB.NET、F#、.NET Core、.NET Standard、.NET Frameworkなど、さまざまな.NETバージョンとプロジェクトタイプをサポートしており、Windows、Linux、macOS、iOS、Androidなどのさまざまな開発環境との互換性を確保します。

IronQRは、QRコードを読み取る能力や生成する能力、複数の画像フォーマットのサポート、QRコードのリサイズ、スタイリング、ロゴの追加などのカスタマイズオプションなどの高度な機能で際立っています。

IronQRの主な機能

IronQRは、基本的なQRコード生成を超え、幅広いQRコード関連のタスクに対応するためのいくつかの機能を提供します。 これらの機能を確認し、コンソール アプリなどのあらゆる種類の .NET アプリケーション テンプレートに統合できるサンプル コードを確認してみましょう。

QRコードの読み取り

IronQRはQRコードのデコードに優れており、ユーザーがQRコードに埋め込まれた情報に簡単にアクセスする方法を提供します。 単純なURLから複雑な埋め込まれた情報まで、QRコードからデータを迅速かつ正確に抽出できます。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-1.cs
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;

IronQr.License.LicenseKey = "License-Key";

// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");

// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(inputImage);

// Initialize the QR Code reader
QrReader qrReader = new QrReader();

// Execute QR Code reading on the provided image
IEnumerable<QrResult> qrResults = qrReader.Read(qrInput);

// Assuming you have the QR results in qrResults as before
foreach (var result in qrResults)
{
    Console.WriteLine(result.Value); // Print the QR code content to the console
}
Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic

IronQr.License.LicenseKey = "License-Key"

' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")

' Prepare the image for QR code detection
Dim qrInput As New QrImageInput(inputImage)

' Initialize the QR Code reader
Dim qrReader As New QrReader()

' Execute QR Code reading on the provided image
Dim qrResults As IEnumerable(Of QrResult) = qrReader.Read(qrInput)

' Assuming you have the QR results in qrResults as before
For Each result In qrResults
	Console.WriteLine(result.Value) ' Print the QR code content to the console
Next result
$vbLabelText   $csharpLabel

このプロセスは、必要な名前空間 (IronQr と Iron Software.Drawing) を組み込むことから始まります。画像操作を処理するために、Iron Software.Drawing 名前空間の Color を具体的に指定します。

QRコードの読み取りプロセスに入る前に、IronQr.License.LicenseKeyにライセンスキーを割り当ててソフトウェアをアクティブにする必要があります。 コードは次に、AnyBitmap.FromFile("QRCode.png")を使用してファイルからQRコード画像をロードします。

画像がロードされたら、次にQRコード検出の準備をします。 この準備は、画像のコンテナとして機能するQrImageInputオブジェクトを作成することで行われます。

この機能の中核はQrReaderクラスにあり、これはインスタンス化され、QRコードの読み取り操作を実行するために使用されます。 リーダーは準備された画像を分析し、そこに含まれる QR コードを検索します。 この操作の結果は、画像内に検出された各QRコードを表すQrResultオブジェクトのコレクションです。

QRコードにエンコードされたデータにアクセスして利用するために、コードはforeachループを使用して結果のコレクションを反復処理します。各QrResultオブジェクトには、QRコードの値のようなプロパティが含まれており、これにアクセスして表示することができます。

カスタムQR読み取りモードオプション

IronQR は、QR コードを読み取るためのさまざまなモードを提供しており、さまざまなニーズに柔軟に対応できます。

-混合スキャンモード: 速度と精度のバランスをとります。鮮明でない QR コードや部分的に隠れている QR コードに役立ちます。 -機械学習 (ML) スキャン モード: 高度なテクノロジーを使用して、破損した QR コードや読み取りにくい QR コードを読み取ります。検出が難しいシナリオに最適です。 -基本スキャン モード: 明確でわかりやすい QR コードを読み取るための、最もシンプルで最速の方法です。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-2.cs
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using System.Collections.Generic;

IronQr.License.LicenseKey = "License-Key";

// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");

QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);

QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);

QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports System.Collections.Generic

IronQr.License.LicenseKey = "License-Key"

' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")

Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mixedScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mixedScanInput)

Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mlScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mlScanInput)

Dim basicScanInput As New QrImageInput(inputImage, QrScanMode.OnlyBasicScan)
Dim basicScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(basicScanInput)
$vbLabelText   $csharpLabel

高度なQRコードの読み取り

IronQR の高度な QR コード読み取り機能は、QR コードのスキャンとデコードに対する包括的なアプローチを提供します。 この機能セットは基本的な読み取りを超え、より深いレベルのインタラクションとデータ抽出を提供します。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-3.cs
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;

IronQr.License.LicenseKey = "License-Key";

var imageToScan = AnyBitmap.FromFile("QRCode.png");

QrImageInput qrInput = new QrImageInput(imageToScan);

QrReader qrScanner = new QrReader();

IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);

foreach (QrResult qrResult in scanResults)
{

    Console.WriteLine(qrResult.Value);

    Console.WriteLine(qrResult.Url);

    foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points)
    {
        Console.WriteLine($"{coordinate.X}, {coordinate.Y}");
    }
}
Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic

IronQr.License.LicenseKey = "License-Key"

Dim imageToScan = AnyBitmap.FromFile("QRCode.png")

Dim qrInput As New QrImageInput(imageToScan)

Dim qrScanner As New QrReader()

Dim scanResults As IEnumerable(Of QrResult) = qrScanner.Read(qrInput)

For Each qrResult As QrResult In scanResults

	Console.WriteLine(qrResult.Value)

	Console.WriteLine(qrResult.Url)

	For Each coordinate As IronSoftware.Drawing.PointF In qrResult.Points
		Console.WriteLine($"{coordinate.X}, {coordinate.Y}")
	Next coordinate
Next qrResult
$vbLabelText   $csharpLabel

C# アプリケーションで IronQR ライブラリを使用して QR コード ジェネレーターを作成するには、次の手順に注意深く従ってください。 このガイドは、Windowsフォームアプリケーションのセットアップ、IronQRライブラリのインストール、QRコードを生成するコードの記述、および出力の理解を案内します。

ステップ1: Visual StudioでWindowsアプリケーションを作成

  1. まず、コンピューターで Visual Studio を起動します。
  2. "新しいプロジェクトの作成"ボタンをクリックします。
  3. プロジェクトの種類としてWindows フォーム アプリを選択します。 言語にはC#を選んでください。

! Windows フォーム アプリ

  1. プロジェクトの名前を入力し、保存場所を選択します。 次の画面で.NET frameworkを選択します。 作成をクリックします。

プロジェクト構成

ステップ2: IronQRライブラリをインストール

プロジェクトにIronQRライブラリをインストールする時です。 IronQRライブラリは異なる方法でインストールできます。

NuGetパッケージマネージャーを使用してインストール

  1. ソリューション エクスプローラーでプロジェクトを右クリックし、 [NuGet パッケージの管理]を選択します。
  2. 検索ボックスにIronQRと入力し、 Enter キーを押します。 ! NuGet パッケージの管理
  3. リストでIronQR を見つけて、その横にある[インストール]をクリックします。

! IronQRをインストールする

NuGetパッケージマネージャーコンソールを使用してインストール

  1. [ツール] > [NuGet パッケージ マネージャー] > [パッケージ マネージャー コンソール]に移動します。
    NuGet パッケージマネージャー
  2. Install-Package IronQR "と入力し、Enter キーを押します。
IronQRのインストール

ステップ3: フロントエンドをデザインする

QR Code Generator

3.1 タイトルヘッダー

QRコードを生成する

QRコードジェネレーターアプリケーションを起動すると、すぐに"QR Generator IronQR"というタイトルの太くて権威あるフォントによる目立つヘッダーが表示されます。

3.2 入力セクション

QRコード用のテキスト入力

ユーザーは QR コードにエンコードしたいデータを入力できます。

ロゴの選択

ロゴを選択

"ロゴを選択"領域では、さらにカスタマイズを行うことができます。 ユーザーは、QR コードに埋め込まれるロゴをアップロードできます。

カラー設定

背景色

色選択ボタンを使用すると、ユーザーは QR コードのパレットをカスタマイズできます。

3.3 スタイルパラメータ

スタイリング

カラーカスタマイズツールに隣接して、"次元"を入力するためのエリアがあります。この数値設定は、QRコードの全体的なサイズを決定し、名刺、フライヤー、デジタルスクリーンなど、意図されたディスプレイのコンテキストにぴったり合うようにします。

ユーザーが QR コードの全体的なサイズを指定できるようにします。

次元入力の隣に"余白"フィールドがあり、QRコードの周囲の余白を指定することができます。

ユーザーが QR コードの周囲の空白を指定できるようにします。

C#でQRコードジェネレーターアプリケーションを作成する方法:図17 - QR出力

生成された QR コードのリアルタイム プレビューを提供します。

QR出力

3.5 アクションボタン

QRを生成

QR コード作成プロセスをトリガーします。

C# での QR コード

QRコードを保存

QR コードを保存するための保存ダイアログを開きます。

保存する

C#でQRコードジェネレーターアプリケーションを作成する方法:図20 - リセット

以前の入力と選択をすべてクリアします。

リセット

4.1 セットアップと初期化

まず、アプリケーションは必要な名前空間IronQrIron Software.Drawingを含めることから始まります。

必要な名前空間が含まれています: IronQr および Iron Software.Drawing。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-4.cs
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;

Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
$vbLabelText   $csharpLabel
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-5.cs
public QR_Generator()
{
    InitializeComponent();
    SetLicenseKey();
    EnsureDirectoryExists(qrCodesDirectory);
}
'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
'ORIGINAL LINE: public QR_Generator()
Public Sub New()
	InitializeComponent()
	SetLicenseKey()
	EnsureDirectoryExists(qrCodesDirectory)
End Sub
$vbLabelText   $csharpLabel

IronQRが制限なしに操作することを保証するために、有効なライセンスキーを適用する必要があります。

IronQR ライブラリに有効なライセンス キーを適用します。

private static void SetLicenseKey() {
    IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}
private static void SetLicenseKey() {
    IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}
Private Shared Sub SetLicenseKey()
	IronQr.License.LicenseKey = "YOUR_LICENSE_KEY"
End Sub
$vbLabelText   $csharpLabel

&quot;YOUR_LICENSE_KEY&quot;を実際のライセンス キーに置き換えます。

4.3 ディレクトリ管理

必要なディレクトリをチェックまたは作成します。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-7.cs
private static void EnsureDirectoryExists(string path)
{
    if (!System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path);
    }
}
Private Shared Sub EnsureDirectoryExists(ByVal path As String)
	If Not System.IO.Directory.Exists(path) Then
		System.IO.Directory.CreateDirectory(path)
	End If
End Sub
$vbLabelText   $csharpLabel

QR コード ディレクトリへのパスは、QR_Generator クラスのコンストラクターで qrCodesDirectory として定義され、アプリケーションの起動パスと"QR コード"フォルダー名が結合されます。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-8.cs
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
Dim qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")
$vbLabelText   $csharpLabel

4.4 カラー選択

カラー ダイアログ コンポーネントとユーティリティ関数を提供します。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-9.cs
private string ColorToHex(System.Drawing.Color color)
{
    return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
	Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End Function
$vbLabelText   $csharpLabel

UpdateColor メソッドは、選択された色を取得し、16 進文字列を使用して Iron Software.Drawing.Color 形式に変換し、選択内容に応じて QR コードの前景色または背景色を更新します。 重要なルール:
1. 各項目は番号付きでテキストタグで囲まれています:[N] テキスト

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-10.cs
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
    if (select_color.ShowDialog() == DialogResult.OK)
    {
        var hexColor = ColorToHex(select_color.Color);
        targetColor = new Color(hexColor);
        display.BackColor = select_color.Color;
    }
}
Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
	If select_color.ShowDialog() = DialogResult.OK Then
		Dim hexColor = ColorToHex(select_color.Color)
		targetColor = New Color(hexColor)
		display.BackColor = select_color.Color
	End If
End Sub
$vbLabelText   $csharpLabel

4.5 ロゴの追加

ユーザーがロゴを選択できるようにします。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-11.cs
private void btn_logo_Click(object sender, EventArgs e)
{
    if (select_logo.ShowDialog() == DialogResult.OK)
    {
        try
        {
            logoBmp = new AnyBitmap(select_logo.FileName);
            selected_logo.Image = Image.FromFile(select_logo.FileName);
        }
        catch (Exception ex)
        {
            ShowError("An error occurred while loading the logo", ex.Message);
        }
    }
}
Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
	If select_logo.ShowDialog() = DialogResult.OK Then
		Try
			logoBmp = New AnyBitmap(select_logo.FileName)
			selected_logo.Image = Image.FromFile(select_logo.FileName)
		Catch ex As Exception
			ShowError("An error occurred while loading the logo", ex.Message)
		End Try
	End If
End Sub
$vbLabelText   $csharpLabel

4.6 QRコードの生成

ユーザー入力に基づいて QR コードを生成するロジックが含まれています。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-12.cs
private void btn_generate_Click(object sender, EventArgs e)
{
    GenerateQRCode();
}
Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
	GenerateQRCode()
End Sub
$vbLabelText   $csharpLabel

QrOptions オブジェクトはエラー訂正レベルを定義し、QR コードの損傷や不明瞭化に対する耐性を強化します。 CreateStyleOptions メソッドは、色、寸法、ロゴなどのユーザーのカスタム設定を含む QrStyleOptions オブジェクトを生成します。 詳細は次のメソッドに記載されています:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-14.cs
private QrStyleOptions CreateStyleOptions()
{
    return new QrStyleOptions
    {
        BackgroundColor = bgColor,
        Color = color,
        Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
        Margins = Convert.ToInt32(txt_margin.Value),
        Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
    };
}
Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
	Return New QrStyleOptions With {
		.BackgroundColor = bgColor,
		.Color = color,
		.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
		.Margins = Convert.ToInt32(txt_margin.Value),
		.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
			.Bitmap = logoBmp,
			.Width = 50,
			.Height = 50,
			.CornerRadius = 5
		}, Nothing)
	}
End Function
$vbLabelText   $csharpLabel

4.7 QRコードの保存

生成された QR コードの保存を処理します。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-15.cs
private void btn_save_Click(object sender, EventArgs e)
{
    SaveQRCode();
}

private void SaveQRCode()
{
    if (pictureBox.Image == null)
    {
        MessageBox.Show("There is no QR code to save.", "Error");
        return;
    }

    saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
    saveFileDialog.Title = "Save QR Code";
    saveFileDialog.FileName = "QRCode";

    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        try
        {
            pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
            MessageBox.Show("QR Code has been saved!", "Success");
        }
        catch (Exception ex)
        {
            ShowError("An error occurred while saving the QR code", ex.Message);
        }
    }
}
Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
	SaveQRCode()
End Sub

Private Sub SaveQRCode()
	If pictureBox.Image Is Nothing Then
		MessageBox.Show("There is no QR code to save.", "Error")
		Return
	End If

	saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
	saveFileDialog.Title = "Save QR Code"
	saveFileDialog.FileName = "QRCode"

	If saveFileDialog.ShowDialog() = DialogResult.OK Then
		Try
			pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
			MessageBox.Show("QR Code has been saved!", "Success")
		Catch ex As Exception
			ShowError("An error occurred while saving the QR code", ex.Message)
		End Try
	End If
End Sub
$vbLabelText   $csharpLabel
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-16.cs
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
    return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}
Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
	Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
End Function
$vbLabelText   $csharpLabel

4.8 アプリケーションのリセット

ユーザー入力をクリアし、フォームの状態をリセットします。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-17.cs
private void btn_reset_Click(object sender, EventArgs e)
{
    ResetFields();
}

private void ResetFields()
{
    txt_QR.Text = string.Empty;
    txt_dimension.Value = 200;
    txt_margin.Value = 0;
    bgColor = Color.White;
    color = Color.Black;
    txt_selected_color.BackColor = System.Drawing.Color.White;
    txt_selected_bgcolor.BackColor = System.Drawing.Color.Black;
    logoBmp = null;
    selected_logo.Image = null;
    pictureBox.Image = null;
}
Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
	ResetFields()
End Sub

Private Sub ResetFields()
	txt_QR.Text = String.Empty
	txt_dimension.Value = 200
	txt_margin.Value = 0
	bgColor = Color.White
	color = Color.Black
	txt_selected_color.BackColor = System.Drawing.Color.White
	txt_selected_bgcolor.BackColor = System.Drawing.Color.Black
	logoBmp = Nothing
	selected_logo.Image = Nothing
	pictureBox.Image = Nothing
End Sub
$vbLabelText   $csharpLabel

4.9 エラーハンドリング

ユーザーにエラー メッセージを表示します。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-18.cs
private static void ShowError(string title, string message)
{
    MessageBox.Show($"{title}: {message}", "Error");
}
Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
	MessageBox.Show($"{title}: {message}", "Error")
End Sub
$vbLabelText   $csharpLabel

ステップ5: アプリケーションの実行

上記のすべての機能を組み合わせた完全なコードは、プロジェクトにリンクされているサンプル ファイルにあります。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-19.cs
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;

namespace IronQR_QR_Generator_WinForms
{
    public partial class QR_Generator : Form
    {
        string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
        Color bgColor = Color.White;
        Color color = Color.Black;
        AnyBitmap? logoBmp = null;

        public QR_Generator()
        {
            InitializeComponent();
            SetLicenseKey();
            EnsureDirectoryExists(qrCodesDirectory);
        }

        private static void SetLicenseKey()
        {
            IronQr.License.LicenseKey = "License-Key";
        }

        private static void EnsureDirectoryExists(string path)
        {
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
        }

        private void btn_color_Click(object sender, EventArgs e)
        {
            UpdateColor(ref color, txt_selected_color, false);
        }

        private void btn_background_Click(object sender, EventArgs e)
        {
            UpdateColor(ref bgColor, txt_selected_bgcolor, true);
        }

        private string ColorToHex(System.Drawing.Color color)
        {
            return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
        }
        private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
        {
            if (select_color.ShowDialog() == DialogResult.OK)
            {

                var hexColor = ColorToHex(select_color.Color);
                targetColor = new Color(hexColor);
                display.BackColor = select_color.Color;
            }
        }

        private void btn_logo_Click(object sender, EventArgs e)
        {
            if (select_logo.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    logoBmp = new AnyBitmap(select_logo.FileName);
                    selected_logo.Image = Image.FromFile(select_logo.FileName);
                }
                catch (Exception ex)
                {
                    ShowError("An error occurred while loading the logo", ex.Message);
                }
            }
        }

        private void btn_generate_Click(object sender, EventArgs e)
        {
            GenerateQRCode();
        }

        private void GenerateQRCode()
        {
            try
            {
                var options = new QrOptions(QrErrorCorrectionLevel.High);
                var myQr = QrWriter.Write(txt_QR.Text, options);
                var style = CreateStyleOptions();
                var qrImage = myQr.Save(style);
                var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
                var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
                qrImage.SaveAs(fullPath);
                pictureBox.Image = Image.FromFile(fullPath);
            }
            catch (Exception ex)
            {
                ShowError("An error occurred during QR code generation or saving", ex.Message);
            }
        }

        private QrStyleOptions CreateStyleOptions()
        {
            return new QrStyleOptions
            {
                BackgroundColor = bgColor,
                Color = color,
                Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
                Margins = Convert.ToInt32(txt_margin.Value),
                Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
            };
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            SaveQRCode();
        }

        private void SaveQRCode()
        {
            if (pictureBox.Image == null)
            {
                MessageBox.Show("There is no QR code to save.", "Error");
                return;
            }

            saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
            saveFileDialog.Title = "Save QR Code";
            saveFileDialog.FileName = "QRCode";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
                    MessageBox.Show("QR Code has been saved!", "Success");
                }
                catch (Exception ex)
                {
                    ShowError("An error occurred while saving the QR code", ex.Message);
                }
            }
        }

        private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
        {
            return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
        }

        private void btn_reset_Click(object sender, EventArgs e)
        {
            ResetFields();
        }

        private void ResetFields()
        {
            txt_QR.Text = string.Empty;
            txt_dimension.Value = 200;
            txt_margin.Value = 0;
            bgColor = Color.White;
            color = Color.Black;
            txt_selected_color.BackColor = bgColor;
            txt_selected_bgcolor.BackColor = color;
            logoBmp = null;
            selected_logo.Image = null;
            pictureBox.Image = null;
        }

        private static void ShowError(string title, string message)
        {
            MessageBox.Show($"{title}: {message}", "Error");
        }
    }
}
Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color

Namespace IronQR_QR_Generator_WinForms
	Partial Public Class QR_Generator
		Inherits Form

		Private qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")
		Private bgColor As Color = Color.White
		Private color As Color = Color.Black
		Private logoBmp? As AnyBitmap = Nothing

		Public Sub New()
			InitializeComponent()
			SetLicenseKey()
			EnsureDirectoryExists(qrCodesDirectory)
		End Sub

		Private Shared Sub SetLicenseKey()
			IronQr.License.LicenseKey = "License-Key"
		End Sub

		Private Shared Sub EnsureDirectoryExists(ByVal path As String)
			If Not System.IO.Directory.Exists(path) Then
				System.IO.Directory.CreateDirectory(path)
			End If
		End Sub

		Private Sub btn_color_Click(ByVal sender As Object, ByVal e As EventArgs)
			UpdateColor(color, txt_selected_color, False)
		End Sub

		Private Sub btn_background_Click(ByVal sender As Object, ByVal e As EventArgs)
			UpdateColor(bgColor, txt_selected_bgcolor, True)
		End Sub

		Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
			Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
		End Function
		Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
			If select_color.ShowDialog() = System.Windows.Forms.DialogResult.OK Then

				Dim hexColor = ColorToHex(select_color.Color)
				targetColor = New Color(hexColor)
				display.BackColor = select_color.Color
			End If
		End Sub

		Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
			If select_logo.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
				Try
					logoBmp = New AnyBitmap(select_logo.FileName)
					selected_logo.Image = Image.FromFile(select_logo.FileName)
				Catch ex As Exception
					ShowError("An error occurred while loading the logo", ex.Message)
				End Try
			End If
		End Sub

		Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
			GenerateQRCode()
		End Sub

		Private Sub GenerateQRCode()
			Try
				Dim options = New QrOptions(QrErrorCorrectionLevel.High)
				Dim myQr = QrWriter.Write(txt_QR.Text, options)
				Dim style = CreateStyleOptions()
				Dim qrImage = myQr.Save(style)
				Dim fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png"
				Dim fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName)
				qrImage.SaveAs(fullPath)
				pictureBox.Image = Image.FromFile(fullPath)
			Catch ex As Exception
				ShowError("An error occurred during QR code generation or saving", ex.Message)
			End Try
		End Sub

		Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
			Return New QrStyleOptions With {
				.BackgroundColor = bgColor,
				.Color = color,
				.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
				.Margins = Convert.ToInt32(txt_margin.Value),
				.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
					.Bitmap = logoBmp,
					.Width = 50,
					.Height = 50,
					.CornerRadius = 5
				}, Nothing)
			}
		End Function

		Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
			SaveQRCode()
		End Sub

		Private Sub SaveQRCode()
			If pictureBox.Image Is Nothing Then
				MessageBox.Show("There is no QR code to save.", "Error")
				Return
			End If

			saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
			saveFileDialog.Title = "Save QR Code"
			saveFileDialog.FileName = "QRCode"

			If saveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
				Try
					pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
					MessageBox.Show("QR Code has been saved!", "Success")
				Catch ex As Exception
					ShowError("An error occurred while saving the QR code", ex.Message)
				End Try
			End If
		End Sub

		Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
			Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
		End Function

		Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
			ResetFields()
		End Sub

		Private Sub ResetFields()
			txt_QR.Text = String.Empty
			txt_dimension.Value = 200
			txt_margin.Value = 0
			bgColor = Color.White
			color = Color.Black
			txt_selected_color.BackColor = bgColor
			txt_selected_bgcolor.BackColor = color
			logoBmp = Nothing
			selected_logo.Image = Nothing
			pictureBox.Image = Nothing
		End Sub

		Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
			MessageBox.Show($"{title}: {message}", "Error")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

レイアウトは入力、スタイリング、出力、およびアクションのセクションにきちんと整理されています。

アプリケーションを実行すると、入力、スタイル、出力、アクションのセクションで整理されたメイン ウィンドウが表示されます。 ユーザー インターフェイスに従ってデータを入力し、QR コードをカスタマイズし、必要に応じて QR コードを生成して保存します。

結論

結論として、このガイドはC#アプリケーションでIronQRライブラリを使用してQRコードを生成するプロセスを案内しました。 Visual Studioでプロジェクトをセットアップし、IronQRライブラリを統合し、ユーザーフレンドリーなインターフェースをデザインし、バックエンドロジックを記述する手順を分解することにより、アプリケーションにQRコード機能を追加する方法の簡単さを示しました。

IronQR の機能をさらに詳しく知りたい方には、IronQR が無料トライアルを提供していることに注目する価値があります。 IronQRをプロジェクトに統合することを決定した場合、ライセンスは$799から始まっており、プロ仕様のQRコード生成のための費用対効果の高いソリューションを提供します。

よくある質問

C#でQRコードジェネレーターアプリケーションをどのように作成できますか?

C#でQRコードジェネレーターアプリケーションを作成するには、IronQRライブラリを使用します。Visual StudioでWindows Formsアプリケーションをセットアップし、NuGetを通じてIronQRをインストールし、アプリケーションのフロントエンドを設計します。IronQRの機能を使用して、色選択やロゴの埋め込みなどのQRコード生成ロジックを実装します。

.NET QRコードライブラリを使用する利点は何ですか?

IronQRのような.NET QRコードライブラリは、高い精度のQRコード読み取り、QRコード生成のカスタマイズオプション、さまざまな.NET環境のサポートなどの高度な機能を提供します。また、QRコードのリサイズやスタイリングも可能です。

C#でQRコードを生成する際のエラーをどのように処理しますか?

C#では、try-catchブロックを使用してQRコード生成中に適切なエラー処理メカニズムを実装することでエラーを処理できます。IronQRは、QRコード作成中の問題を効率的に対処するために、スムーズなエラー管理をサポートしています。

QRコードライブラリを使用してQRコードにロゴを埋め込むことはできますか?

はい、IronQRライブラリを使用してQRコードにロゴを埋め込むことができます。この機能により、カスタムロゴをデザインに取り入れることで、QRコードのブランドを強化することができます。

C#アプリケーションで生成されたQRコードをどのように保存しますか?

IronQRの機能を使用してストレージディレクトリを指定することで、C#アプリケーションで生成されたQRコードを保存できます。これにより、アプリケーション内で生成されたQRコードを効率的に管理および保存できます。

QRコードライブラリのライセンスキーを設定するために必要な手順は何ですか?

IronQRのライセンスキーを設定するには、アプリケーションにライセンスコードを組み込む必要があります。これは通常、購入したライセンスでライブラリをアクティブにするためにIronQRから提供される特定のコードラインを追加することを含みます。

C#アプリケーションで特定の色でQRコードをスタイルするにはどうすればよいですか?

IronQRを使用すると、その色のカスタマイズ機能を使用してQRコードを特定の色でスタイルすることができます。アプリケーションに統合された色選択ダイアログを使用して、QRコードの前景と背景の色を選択できます。

Visual StudioでQRコードライブラリをインストールする手順は何ですか?

Visual StudioでIronQRのようなQRコードライブラリをインストールするには、NuGetパッケージマネージャーを使用します。「IronQR」を検索して「インストール」をクリックしてプロジェクトに追加します。代わりに、「パッケージマネージャーコンソール」で「Install-Package IronQR」というコマンドを使用します。

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

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

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

準備はできましたか?
Nuget ダウンロード 51,390 | Version: 2025.11 リリース