C# QRコード生成アプリケーション
IronQRはIron Softwareの最新の.NET QRコードライブラリです。最新の機械学習技術を活用して、どの角度からでも高精度にQRコードを読み取ります。新しいQRコードを簡単に生成およびカスタマイズできます!今すぐIronQRを始めましょう!
このガイドでは、C#を使用してQRコードを作成する方法を紹介します。QRコードと.NETバーコードDLLは、情報を迅速かつ効率的に共有する手段として広く利用されています。アプリの開発やウェブサイトの管理、リンクの手軽な共有など、さまざまな場面で役立ちます。このガイドでは、IronQRを使い、要件に合わせたQRコードを効率的に生成する方法を説明します。このライブラリを使用すると、複雑なロジックを扱わずに、C#で簡単にQRコードを作成できます。作業を始めるために必要な内容を、手順に沿って説明します。アプリにQRコード生成機能を追加したい場合にも、生成の仕組みを知りたい場合にも役立つ内容です。それでは、手順を確認します。
C#でQRコード生成アプリケーションを作成する方法
- Visual Studio で Windows フォーム アプリケーションを作成します
- NuGetを使用してQRライブラリをインストールします
- フォームのフロントエンド要素を設計します
- QRコード生成のロジックを記述します
- アプリケーションを実行し、QRコードの作成を開始します
C# で QR コード生成ライブラリをインストールする
無料トライアルで今日からプロジェクトにIronQRを使用し始めましょう。
始める前に、IronQR NuGetパッケージをインストールする必要があります。
IronQR: C# QRライブラリ
IronQRは、QRコード機能を.NETアプリケーションに統合するための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コードからデータを迅速かつ正確に抽出できます。
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 resultImports 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まず、必要な名前空間であるIronQrとIronSoftware.Drawingをインポートします。画像操作には、IronSoftware.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コードに有用です。
- 機械学習(ML)スキャンモード: ダメージを受けたり、読み取りにくいQRコードを読むための先進技術を使用し、検出が困難な状況に最適です。
- 基本スキャンモード: 最もシンプルで高速な方法で、鮮明で読み取りやすいQRコードに適しています。
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);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)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)高度なQRコードの読み取り
IronQR の高度な QR コード読み取り機能は、QR コードのスキャンとデコードに対する包括的なアプローチを提供します。 この機能セットは基本的な読み取りを超え、より深いレベルのインタラクションとデータ抽出を提供します。
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}");
}
}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 qrResultImports 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 qrResultC# アプリケーションで IronQR ライブラリを使用して QR コード ジェネレーターを作成するには、次の手順に注意深く従ってください。 このガイドは、Windowsフォームアプリケーションのセットアップ、IronQRライブラリのインストール、QRコードを生成するコードの記述、および出力の理解を案内します。
ステップ1: Visual StudioでWindowsアプリケーションを作成
-
まず、コンピューターで Visual Studio を起動します。
-
「新しいプロジェクトの作成」ボタンをクリックします。
-
プロジェクトの種類としてWindows フォーム アプリを選択します。 言語にはC#を選んでください。

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

ステップ2: IronQRライブラリをインストール
次に、プロジェクトにIronQRライブラリをインストールします。インストールには、複数の方法があります。
NuGetパッケージマネージャーを使用してインストール
-
ソリューション エクスプローラーでプロジェクトを右クリックし、 [NuGet パッケージの管理]を選択します。
-
検索ボックスに
IronQRと入力してEnterを押します。
-
リストでIronQRを見つけて、その横にある[インストール]をクリックします。

NuGetパッケージマネージャーコンソールを使用してインストール
- [ツール] > [NuGet パッケージ マネージャー] > [パッケージ マネージャー コンソール]に移動します。

Install-Package IronQrを入力してEnterを押します。

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

3.1 タイトルヘッダー

QRコード生成アプリケーションを起動すると、太字の力強いフォントで「QR Generator IronQR」と記された、目を引くヘッダーが表示されます。
3.2 入力セクション
QRコード用のテキスト入力
ユーザーは QR コードにエンコードしたいデータを入力できます。
ロゴの選択

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

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

サイズ設定
ユーザーが QR コードの全体的なサイズを指定できるようにします。
余白設定
ユーザーが QR コードの周囲の空白を指定できるようにします。
3.4 出力プレビュー
生成された QR コードのリアルタイム プレビューを提供します。

3.5 アクションボタン
QRを生成
QR コード作成プロセスをトリガーします。

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

フォームをリセット
以前の入力と選択をすべてクリアします。

ステップ4: バックエンドロジックを書く
4.1 セットアップと初期化
必要な名前空間を含めます:IronQrおよびIronSoftware.Drawing。
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.ColorImports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Colorpublic QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}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'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 Sub4.2 ライセンスキーの設定
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 SubPrivate Shared Sub SetLicenseKey()
IronQr.License.LicenseKey = "YOUR_LICENSE_KEY"
End Sub"YOUR_LICENSE_KEY"を実際のライセンスキーに置き換えてください。
4.3 ディレクトリ管理
必要なディレクトリをチェックまたは作成します。
private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}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 SubPrivate Shared Sub EnsureDirectoryExists(ByVal path As String)
If Not System.IO.Directory.Exists(path) Then
System.IO.Directory.CreateDirectory(path)
End If
End SubQRコードディレクトリのパスは、QR_Generatorクラスのコンストラクタ内でqrCodesDirectoryとして定義されます。これは、アプリケーションの起動パスと「QR Codes」というフォルダ名を組み合わせたものです。
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");Dim qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")Dim qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")4.4 カラー選択
カラー ダイアログ コンポーネントとユーティリティ関数を提供します。
private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}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 FunctionPrivate Function ColorToHex(ByVal color As System.Drawing.Color) As String
Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End FunctionUpdateColorメソッドは選択された色を受け取り、16進文字列を使ってIronSoftware.Drawing.Color形式に変換し、選択に応じてQRコードの前景色または背景色を更新します。 また、新しい色の選択を反映するように UI も更新します:
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 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 SubPrivate 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 Sub4.5 ロゴの追加
ユーザーがロゴを選択できるようにします。
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_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 SubPrivate 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 Sub4.6 QRコードの生成
ユーザー入力に基づいて QR コードを生成するロジックが含まれています。
private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}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 SubPrivate Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End SubQrOptionsオブジェクトは、QRコードの損傷や遮蔽に対する耐性を高めるエラー訂正レベルを定義します。 CreateStyleOptionsメソッドは、ユーザーのカスタム設定(色、寸法、ロゴなど)を含むQrStyleOptionsオブジェクトを生成します。 詳細は次のメソッドに記載されています:
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 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 FunctionPrivate 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 Function4.7 QRコードの保存
生成された QR コードの保存を処理します。
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 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 SubPrivate 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 Subprivate 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 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 FunctionPrivate 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 Function4.8 アプリケーションのリセット
ユーザー入力をクリアし、フォームの状態をリセットします。
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 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 SubPrivate 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 Sub4.9 エラーハンドリング
ユーザーにエラー メッセージを表示します。
private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}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 SubPrivate Shared Sub ShowError(ByVal title As String, ByVal message As String)
MessageBox.Show($"{title}: {message}", "Error")
End Sub4.10 完全なコード例
上記のすべての機能を組み合わせた完全なコードは、プロジェクトにリンクされているサンプル ファイルにあります。
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");
}
}
}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 NamespaceImports 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ステップ5: アプリケーションを実行
アプリケーションを実行すると、入力、スタイル、出力、アクションのセクションで整理されたメイン ウィンドウが表示されます。 ユーザー インターフェイスに従ってデータを入力し、QR コードをカスタマイズし、必要に応じて QR コードを生成して保存します。
結論
????????C#?????????IronQR??????????QR??????????????????Visual Studio????????????????IronQR?????????????????????????????????????????????????????QR???????????????????????
IronQR?????????????????????IronQR?????????????????????$999???????????QR????????????????????????????
よくある質問
IronQRとは?
IronQRはIron Softwareの.NET QRコードライブラリです。.NETアプリケーションにQRコード機能を統合し、さまざまな.NETバージョンに対応し、QRコードの読み取り、生成、カスタマイズなどの機能を提供します。
C#プロジェクトにIronQRをインストールするにはどうすればよいですか?
IronQRは、NuGetパッケージマネージャーを使用して「IronQR」を検索し、インストールをクリックするか、NuGetパッケージマネージャーコンソールで「Install-Package IronQR」と入力してインストールできます。
IronQRを使用してC#でQRコードジェネレーターを作成する手順は何ですか?
QRコードジェネレーターを作成するには、Visual StudioでWindowsフォームアプリケーションを作成し、IronQRをインストールし、UIをデザインし、QRコード生成のロジックを書き、最終的にアプリケーションを実行してQRコードを生成します。
IronQRで生成されたQRコードをカスタマイズできますか?
はい、IronQRでは、寸法、余白、色を設定することでQRコードをカスタマイズでき、ロゴの追加による個別のQRコードデザインも可能です。
IronQRにおけるライセンスキーの役割は何ですか?
ライセンスキーはIronQRライブラリの機能をアクティブにするために必要です。QRコード生成および読み取りの完全な機能を有効にするために、アプリケーションコードにライセンスキーを設定します。
IronQRで利用可能な異なるスキャンモードは何ですか?
IronQRは、速度と精度のバランスを取り、損傷または読み取りが困難なQRコードを含むさまざまなQRコード条件に対応するために、混合スキャンモード、機械学習スキャンモード、および基本スキャンモードを提供します。
IronQRはQRコード読み取りをどのように処理しますか?
IronQRは、画像を読み込み、検出の準備をし、QrReaderを使用して効果的に埋め込まれたデータを分析・抽出する簡単な方法を提供します。
IronQRは異なる開発環境で互換性がありますか?
はい、IronQRは幅広い.NETプロジェクトタイプをサポートしており、Windows、Linux、macOS、iOS、Androidなどのさまざまな環境と互換性があります。
IronQR使用時のエラー処理の推奨方法は何ですか?
QRコード生成または読み取り中に発生する可能性のある例外をキャッチするために、アプリケーションでエラー処理を実装することが推奨され、スムーズな体験を確保します。
QRコードジェネレーターアプリケーションを異なるプラットフォームで実行できますか?
はい、さまざまな.NETフレームワークでのIronQRの互換性により、Windows、Linux、macOSのような複数のプラットフォームでQRコードジェネレーターアプリケーションを実行できます。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。