跳過到頁腳內容
使用 IRONQR

如何在 C# 中創建 QR 碼生成器應用程序

歡迎閱讀我們使用 C# 建立二維碼的指南! 二維碼和 .NET 條碼 DLL 已成為快速且有效率地共享資訊的流行方式。 無論您是在開發應用程式、管理網站,還是只是想尋找一種簡潔的方式來分享鏈接,這些程式碼都非常有用。 在本指南中,我們將示範如何使用IronQR有效地產生二維碼,確保您可以產生符合您需求的二維碼。 這個函式庫讓任何使用 C# 的人都能輕鬆建立二維碼,而無需了解複雜的邏輯。 我們將一步一步地指導您,確保您擁有開始所需的一切。 無論您是想為您的應用程式添加二維碼生成器功能,還是只是好奇它是如何實現的,您都來對了地方。 我們開始吧。

如何在 C# 中建立二維碼產生器

  1. 在 Visual Studio 中建立一個 Windows 窗體應用程式
  2. 使用 NuGet 安裝 QR 函式庫
  3. 設計表單前端元素
  4. 編寫二維碼生成邏輯
  5. 運行應用程式並開始建立二維碼

IronQR:C# 二維碼庫

IronQR是一個 C# 二維碼庫,用於將二維碼功能整合到 .NET 應用程式中。 IronQR 支援多種 .NET 版本和專案類型,包括 C#、VB.NET、F#、.NET Core、.NET Standard、.NET Framework 等,可確保與 Windows、Linux、macOS、iOS 和 Android 等各種開發環境相容。

IronQR 以其先進的功能脫穎而出,包括讀取和生成二維碼支援多種圖像格式以及調整大小、樣式和添加徽標等自訂選項。

IronQR 的一些主要特點

IronQR 的功能不僅限於基本的二維碼生成,還提供多種功能,旨在滿足各種與二維碼相關的任務。 讓我們一起來了解這些功能並查看它們的範例程式碼,您可以將這些程式碼整合到任何類型的 .NET 應用程式範本中,例如控制台應用程式。

讀取二維碼

IronQR 擅長解碼二維碼,為使用者提供了一種直接存取二維碼中嵌入資訊的方法。 您可以快速且準確地從二維碼中提取資料,從簡單的網址到複雜的嵌入式資訊。

using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;

// Set the license key for IronQR
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);

// Print the value of each QR code found in the image
foreach (var result in qrResults)
{
    Console.WriteLine(result.Value);
}
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;

// Set the license key for IronQR
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);

// Print the value of each QR code found in the image
foreach (var result in qrResults)
{
    Console.WriteLine(result.Value);
}
Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color

' Set the license key for IronQR
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)

' Print the value of each QR code found in the image
For Each result In qrResults
	Console.WriteLine(result.Value)
Next result
$vbLabelText   $csharpLabel

我們使用以下二維碼進行掃描:

如何在 C# 中建立二維碼產生器應用程式:圖 1 - 二維碼 PNG 圖像文件

我們得到了以下輸出結果:

如何在 C# 中建立二維碼產生器應用程式:圖 2 - 讀取二維碼輸出

過程首先合併必要的命名空間 IronQrIronSoftware.Drawing,並特別提及 IronSoftware.Drawing 命名空間中的 Color 來處理影像操作。

在開始讀取二維碼之前,必須使用您的許可證金鑰啟動軟體,方法是將其分配給 IronQr.License.LicenseKey。 然後,程式碼繼續從檔案載入二維碼圖像,使用 AnyBitmap.FromFile("QRCode.png")

圖片載入完畢後,下一步是準備進行二維碼偵測。 此準備工作是透過建立一個 QrImageInput 物件來完成的,該物件用作映像的容器。

此功能的核心在於 QrReader 類,該類被實例化並用於執行二維碼讀取操作。 閱讀器分析準備好的圖像 qrInput,尋找其中包含的任何二維碼。 此操作的結果是一組 QrResult 對象,每個對象代表影像中偵測到的二維碼。

為了存取和使用二維碼中編碼的數據,該程式碼使用循環遍歷結果集合。每個物件都包含諸如二維碼值之類的屬性,這些屬性可以被存取和顯示。

自訂二維碼讀取模式選項

IronQR 提供多種從影像中讀取二維碼的方式,使其能夠滿足各種不同的需求。 其中一個選擇是混合掃描模式,它兼顧速度和準確性,當二維碼不清晰或部分被遮蔽時非常有用。

另一種是機器學習(ML)掃描模式,它利用智慧技術讀取損壞或通常不易讀取的二維碼。 這種模式非常適合二維碼難以偵測的複雜情況。

最後,還有基本掃描模式,是掃描清晰簡潔的二維碼最快、最簡單的方法。 當您需要快速獲得結果且二維碼易於讀取時,它是最佳選擇。

using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;

// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";

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

// Using mixed scan mode
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);

// Using machine learning scan mode
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);

// Using basic scan mode
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;

// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";

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

// Using mixed scan mode
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);

// Using machine learning scan mode
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);

// Using basic scan mode
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color

' Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key"

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

' Using mixed scan mode
Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mixedScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mixedScanInput)

' Using machine learning scan mode
Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mlScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mlScanInput)

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

讀取高級二維碼

IronQR 的先進二維碼讀取功能旨在為二維碼掃描和解碼提供全面而細緻的方法。 此功能集超越了基本的二維碼讀取功能,提供了更深層的互動和資料擷取。

using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;

// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";

// Load the image to scan
var imageToScan = AnyBitmap.FromFile("QRCode.png");

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

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

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

// Print the value, URL, and coordinates of each QR code found in the image
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 IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;

// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";

// Load the image to scan
var imageToScan = AnyBitmap.FromFile("QRCode.png");

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

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

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

// Print the value, URL, and coordinates of each QR code found in the image
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 IronQr.Enum
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color

' Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key"

' Load the image to scan
Dim imageToScan = AnyBitmap.FromFile("QRCode.png")

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

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

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

' Print the value, URL, and coordinates of each QR code found in the image
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

這是使用 IronQR 掃描二維碼後的輸出結果:

如何在 C# 中建立二維碼產生器應用程式:圖 3 - 掃描二維碼輸出

我們使用以下二維碼:

如何在 C# 中建立二維碼產生器應用程式:圖 4 - 二維碼輸入

每個 QrResult 物件提供圖像中二維碼的解碼資料 (Value)、任何嵌入的 URL (Url) 和空間座標 (Points) 的存取。

IronQR 會為檢測到的每個二維碼提供詳細信息,包括二維碼中的確切內容和任何 URL。 此外,該庫還提供了圖像中二維碼角點的精確座標(透過 Points 屬性)。

若要在 C# 應用程式中使用 IronQR 二維碼庫建立二維碼產生器,請仔細按照下列步驟操作。 本指南將引導您完成設定 Windows 窗體應用程式、安裝 IronQR 程式庫、編寫產生二維碼的程式碼以及了解輸出結果的過程。

步驟 1:在 Visual Studio 中建立 Windows 應用程式

首先,在您的電腦上啟動 Visual Studio。

它將在 Visual Studio 中建立並開啟一個 Windows 窗體應用程式。

步驟 2:安裝 IronQR 庫

現在是時候在專案中安裝 IronQR 庫了。 您可以透過不同的方法安裝 IronQR 庫。 選擇符合您喜好的選項:

使用 NuGet 套件管理器進行安裝

使用 NuGet 套件管理器控制台進行安裝

  • 前往"工具" > "NuGet 套件管理員" > "套件管理員控制台"

如何在 C# 中建立二維碼產生器應用程式:圖 9 - NuGet 套件管理器

輸入Install-Package IronQR並按 Enter 鍵。

如何在 C# 中建立二維碼產生器應用程式:圖 10 - 安裝 IronQR

步驟三:設計前端

如何在 C# 中建立二維碼產生器應用程式:圖 11 - 二維碼產生器

3.1 標題頁眉

如何在 C# 中建立二維碼產生器應用程式:圖 12 - 產生二維碼

啟動二維碼產生器應用程式後,用戶會立即看到一個醒目的標題"QR Generator IronQR",字體粗體且權威。 字體 Agency FB 因其簡潔現代的線條而被選中,給人一種高效和精準的感覺。 標題採用醒目的 48 號字體,既突出又有力,能夠吸引用戶的注意力,並牢牢確立應用程式的身份。

3.2 輸入部分

二維碼文字輸入

如何在 C# 中建立二維碼產生器應用程式:圖 13 - 二維碼文字輸入

輸入部分的核心是一個簡單而基本的元件:文字輸入框。 在這裡,使用者可以輸入他們想要編碼到二維碼中的資料。 這個框空間很大,可以容納大量文字,而且位置顯眼,靠近頂部。

標誌選擇

如何在 C# 中建立二維碼產生器應用程式:圖 14 - 選擇徽標

在文字輸入框下方,"選擇徽標"區域允許進行額外的自訂設定。 用戶可以上傳徽標,該徽標將嵌入二維碼中,從而增強品牌識別度或個人化二維碼。 旁邊的圖片框提供了所選徽標的預覽,提供即時的視覺回饋。

色彩配置

如何在 C# 中建立二維碼產生器應用程式:圖 15 - 背景顏色

向右移動,介面會顯示顏色選擇選項。 兩個按鈕,一個用於設定二維碼顏色,另一個用於設定背景顏色,使用戶能夠自訂二維碼的調色板。 這些按鈕旁邊的富文本方塊顯示目前選定的顏色。

輸入部分的佈局經過精心設計,包括文字、徽標和顏色選項,體現了在創建二維碼時對使用者優先事項的清晰理解。 它兼具功能性和靈活性,使用戶能夠快速且有效率地輸入必要訊息,同時也為創造力提供了空間。

3.3 樣式參數

如何在 C# 中建立二維碼產生器應用程式:圖 16 - 樣式

尺寸設定

在顏色自訂工具旁邊,使用者可以找到"尺寸"輸入框。這個數值設定至關重要,因為它決定了二維碼的整體大小,確保它能完美地適應預期的顯示環境,無論是名片、傳單還是電子螢幕。

邊距設定

在尺寸輸入框旁邊,"邊距"欄位可讓使用者指定二維碼周圍的空白區域。 頁邊距不僅僅是一種美觀的選擇;它是一個功能性元素,會影響掃描器對二維碼的讀取。 該應用程式提供了一個數值上下控制按鈕,方便使用者輕鬆調整此參數。

3.4 輸出預覽

如何在 C# 中建立二維碼產生器應用程式:圖 17 - 二維碼輸出

使用者啟動二維碼產生後,表單左側標示"輸出"的大圖片框就成為焦點。 它可以作為動態顯示屏,即時預覽產生的二維碼。 這種即時的視覺回饋對於使用者驗證他們的設計選擇並確保二維碼符合他們的預期,然後再保存,至關重要。

3.5 操作按鈕

產生二維碼

如何在 C# 中建立二維碼產生器應用程式:圖 18 - C# 中的二維碼

"產生二維碼"按鈕是應用程式介面中的關鍵控制元素。 此按鈕位於表單的戰略位置,是產生二維碼過程的催化劑。 點擊此按鈕後,應用程式將取得使用者定義的所有輸入資料和樣式參數,並開始產生自訂二維碼。

儲存二維碼

如何在 C# 中建立二維碼產生器應用程式:圖 19 - 儲存

產生二維碼並顯示在輸出預覽區域後,"儲存二維碼"按鈕就會生效。 點擊後,將開啟儲存對話框,允許使用者選擇所需的檔案格式和儲存位置。

重設表單

如何在 C# 中建立二維碼產生器應用程式:圖 20 - 重置

按一下此按鈕,即可清除所有先前的輸入和選擇,將所有設定還原為預設值。 這是該表單的一個重要方面,它提供了一種快速重新初始化應用程式的方法,而無需手動調整每個選項。

第四步:編寫後端邏輯

4.1 設定和初始化

首先,應用程式開始包含必要的命名空間:IronQrIronSoftware.Drawing。 這些命名空間至關重要,因為它們提供了在應用程式中產生和操作二維碼和顏色所需的功能。 自訂 Color 類別被定義,以方便二維碼生成中的顏色管理,覆蓋預設的 System.Drawing.Color 類,以確保與 IronQR 的要求相容。

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.Color
$vbLabelText   $csharpLabel

QR_Generator 類別的建構子在準備應用程式以供使用方面起著至關重要的作用。 應用程式的元件在此初始化,這是 Windows 窗體應用程式中設定窗體 UI 元素的標準步驟。

public 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
$vbLabelText   $csharpLabel
  • SetLicenseKey: 呼叫此方法為 IronQR 函式庫套用有效的許可證金鑰。 對於商業應用,必須使用許可證金鑰才能解鎖 IronQR 庫的全部功能。

  • EnsureDirectoryExists: 考慮到需要儲存產生的二維碼,此方法確保有一個專用目錄可用。 它會檢查應用程式啟動路徑中是否存在"QR Codes"目錄,如果不存在,則會建立該目錄。

4.2 許可證密鑰配置

為確保 IronQR 不受限制地運行,必須套用有效的許可證金鑰。 這是透過 SetLicenseKey 方法實現的,這是一個靜態方法,旨在用您購買或試用許可證金鑰配置庫。 以下程式碼片段示範如何設定許可證密鑰:

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

"YOUR_LICENSE_KEY" 替換為您從 Iron Software 取得的實際許可證金鑰。 此方法在 QR_Generator 類別的構造函數中調用,確保在應用程式啟動時以及在生成任何二維碼之前立即應用許可證。

4.3 目錄管理

該應用程式使用 EnsureDirectoryExists 方法來檢查用於儲存二維碼的指定目錄是否存在。 否則,它會建立該目錄。 此方法接受一個參數,即要檢查或建立的目錄的路徑。 以下是具體實現方式:

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 Sub
$vbLabelText   $csharpLabel

此方法利用 System.IO 命名空間與檔案系統互動。 它首先使用 Directory.Exists 檢查指定路徑的目錄是否存在。 如果目錄不存在(傳回 false),則使用 Directory.CreateDirectory 建立目錄。

QR 碼目錄的路徑在 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")
$vbLabelText   $csharpLabel

4.4 顏色選擇

該應用程式在使用者介面上提供了兩個按鈕,每個按鈕都與一種選擇顏色的方法相關聯:btn_color_Click 用於選擇二維碼顏色,btn_background_Click 用於選擇背景顏色。 這些方法利用顏色對話框讓使用者選擇顏色。

當使用顏色對話方塊選擇顏色時,所選顏色將轉換為十六進位字串格式。 這是必要的,因為 IronQR 庫要求顏色以十六進位格式指定。 轉換是透過 ColorToHex 方法完成的:

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 Function
$vbLabelText   $csharpLabel

UpdateColor 方法取得選定的顏色,並使用十六進位字串將其轉換為 IronSoftware.Drawing.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 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 新增徽標

該應用程式包含一個按鈕( btn_logo_Click ),點擊該按鈕將開啟一個檔案對話框,允許使用者選擇要用作徽標的圖像檔案。 對於希望為其二維碼添加品牌標識的企業或個人而言,此功能至關重要。 以下是標誌選擇和整合流程:

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 Sub
$vbLabelText   $csharpLabel

成功選擇圖像後,應用程式會嘗試載入該圖像並顯示預覽。 然後,將 AnyBitmap 物件 logoBmp 設定為選定的圖像,QR 生成邏輯稍後會使用該圖像。

4.6 二維碼生成

當使用者點擊"生成"按鈕時,生成過程開始,該按鈕與 btn_generate_Click 方法關聯。 此方法充當觸發器,呼叫 GenerateQRCode 函數,其中實際生成邏輯就位於該函數中。

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 Sub
$vbLabelText   $csharpLabel

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 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 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
$vbLabelText   $csharpLabel

QrOptions 物件定義了糾錯級別,增強了二維碼對損壞或遮蔽的抵抗力。 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 Function
$vbLabelText   $csharpLabel

此方法建立一個 QrStyleOptions 對象,然後由二維碼產生邏輯使用該物件來應用使用者的偏好。 選項包括:

  • BackgroundColorColor這些屬性設定二維碼的背景色和前景色,從而實現個性化外觀,以匹配品牌或美學偏好。
  • Dimensions:此屬性決定二維碼的大小,使二維碼能夠靈活地適應不同的上下文或媒介。
  • Margins:此屬性設定二維碼周圍的邊距大小,確保其與周圍元素隔離,這對於可擴展性至關重要。
  • Logo:如果使用者選擇添加徽標,則會在此處配置徽標的特定尺寸和圓角半徑,以獲得更精緻的外觀。

4.7 儲存二維碼

儲存功能由"儲存"按鈕觸發,該按鈕與 btn_save_Click 方法關聯。 此方法呼叫 SaveQRCode,它實作了保存邏輯。 該過程包括顯示儲存檔案對話框,允許使用者選擇二維碼的檔案格式和儲存位置。

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 Sub
$vbLabelText   $csharpLabel

此方法檢查是否存在已產生的二維碼。 如果是這樣,它會向使用者提供將檔案儲存為 PNG 或 JPEG 格式的選項。 DetermineImageFormat 功能可確保圖像根據使用者選擇的檔案副檔名以正確的格式儲存。

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

這種靈活性使用戶能夠選擇最適合自己需求的格式,無論是優先考慮品質(PNG)還是檔案大小(JPEG)。

4.8 重置應用程式

重置功能與"重置"按鈕關聯,按鈕會呼叫 btn_reset_Click 方法。 此方法進而呼叫 ResetFields,該函數旨在清除所有使用者輸入並恢復所有設定的預設值,包括文字欄位、顏色選擇和選定的徽標。

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 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 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
$vbLabelText   $csharpLabel

此方法會重置二維碼生成過程中涉及的每個元件。 例如,它會清除二維碼文字,將尺寸和邊距設為預設值,並刪除任何選定的顏色或徽標。

4.9 錯誤處理

該應用程式使用 ShowError 方法以用戶友好的方式顯示錯誤訊息。 此方法接受兩個參數:標題和訊息,它們向使用者提供有關錯誤的上下文。 以下是具體實現方式:

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 Sub
$vbLabelText   $csharpLabel

應用程式的不同部分都採用了這種方法,以確保在發生錯誤時,能夠及時向用戶發送清晰簡潔的訊息。 例如,如果在載入徽標或產生二維碼的過程中發生錯誤,應用程式會呼叫 ShowError 來顯示有關該問題的詳細資訊。

4.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 Namespace
$vbLabelText   $csharpLabel

步驟 5:運行應用程式

應用程式運行時,主視窗將如圖所示顯示。 佈局清晰地分為輸入、樣式、輸出和操作四個部分。

如何在 C# 中建立二維碼產生器應用程式:圖 21 - 應用程式輸出

第一步是將資料輸入到"輸入二維碼文字"欄位中。 這些資料將構成二維碼的內容,例如網址或文字資訊。 接下來,為了個人化二維碼,我們點擊"選擇標誌"按鈕來選擇一個標誌。 選取後,徽標會清晰地顯示在按鈕旁的預覽框中,確認已融入二維碼設計中。

如何在 C# 中建立二維碼產生器應用程式:圖 22 - Logo

選定標誌後,我們選擇二維碼的前景色和背景色。 點選對應的按鈕後,所選顏色會反映在每個按鈕旁的顏色顯示框中,讓我們立即看到所選顏色,從而得到直覺的確認。

如何在 C# 中建立二維碼產生器應用程式:圖 23 - 顏色選擇

對於這個特定的二維碼,我們將尺寸設為 500,以確保二維碼的大小符合我們的需求,並將邊距調整為 20,這樣可以在二維碼周圍留出緩衝區,以防止掃描問題。

如何在 C# 中建立二維碼產生器應用程式:圖 24 - 尺寸

所有輸入和樣式選項設定完畢後,我們點擊"產生二維碼"按鈕來產生二維碼。 應用程式處理我們的輸入,並在輸出圖片框中顯示新產生的二維碼。

如何在 C# 中建立二維碼產生器應用程式:圖 25 - 讀取二維碼輸出

要儲存產生的二維碼,我們只需點擊"儲存二維碼"按鈕。 此操作會開啟一個儲存對話框,讓我們可以選擇二維碼影像的目標位置和檔案格式。

如何在 C# 中建立二維碼產生器應用程式:圖 26 - 儲存對話框

儲存成功後,會顯示成功訊息,確認二維碼已成功儲存。

如何在 C# 中建立二維碼產生器應用程式:圖 27 - 成功訊息

如果需要重新開始或建立新的二維碼,點擊"重置表單"按鈕會將表單恢復到原始狀態,清除所有欄位和選擇,為下一次二維碼產生做好準備。

如何在 C# 中建立二維碼產生器應用程式:圖 28 - 重設表單

以下是IronQR產生的已儲存二維碼:

如何在 C# 中建立二維碼產生器應用程式:圖 29 - 二維碼輸出

結論

總而言之,本指南已引導您完成在 C# 應用程式中使用 IronQR 庫產生二維碼的過程。 透過在 Visual Studio 中設定專案、整合 IronQR 庫、設計使用者友好的介面以及編寫後端邏輯等步驟,我們示範了為應用程式添加二維碼功能是多麼容易。

對於有興趣進一步探索 IronQR 功能的人來說,值得注意的是,IronQR 提供免費試用版,幫助您入門。 如果您決定將 IronQR 整合到您的專案中,許可證起價為 $799,為專業級二維碼產生提供經濟高效的解決方案。

常見問題解答

如何在 C# 中創建一個 QR 代碼生成器應用程式?

若要在 C# 中創建一個 QR 代碼生成器應用程式,從在 Visual Studio 中設置 Windows Forms 應用程式開始,通過 NuGet 安裝 IronQR 庫,設計包含文本、徽標和顏色輸入欄位的界面,然後使用 IronQR 的方法實現 QR 代碼生成邏輯。

在 C# 中,QR 代碼有哪些自定義選項?

IronQR 為 QR 代碼提供自定義選項,如更改顏色、尺寸和邊距。您還可以通過調整 QrStyleOptions 對象中的設置來向 QR 代碼添加徽標。

如何在 C# 項目中安裝 QR 代碼庫?

使用 Visual Studio 中的 NuGet 包管理器在您的 C# 項目中安裝 IronQR 庫。搜索 IronQR 並點擊"安裝"按鈕以將其添加到您的項目中。

在 C# 中,我可以使用哪些格式保存生成的 QR 代碼?

使用IronQR,您可以將生成的QR碼保存為各種格式,包括PNG和JPEG,這使得在質量和檔案大小方面具有靈活性。

我可以使用 C# 庫讀取 QR 代碼嗎?

是的,IronQR 包含讀取 QR 代碼的功能,讓您能夠有效地解碼和提取 QR 圖像中的數據。

使用 C# QR 代碼庫有哪些好處?

像 IronQR 這樣的 C# QR 代碼庫簡化了生成和讀取 QR 代碼的過程,提供多格式支持、自定義選項以及與各種 .NET 版本的兼容性等功能。

如何在 C# 中處理生成 QR 代碼的錯誤?

錯誤處理可以通過在您的 QR 代碼生成應用程式中使用 try-catch 塊來進行。這可確保在 QR 代碼創建過程中發生的任何問題得到妥善管理,提供用戶友好的反饋。

我需要許可證才能在 C# 應用程式中使用 QR 代碼庫嗎?

是的,要無限制地使用 IronQR,您需要一個有效的許可證密鑰。可以提供試用版進行初步測試,專業許可證可供購買以獲得完全訪問。

我該如何在 C# 中將徽標整合到 QR 代碼中?

使用 IronQR,您可以通過在 QrStyleOptions 對象中設置徽標圖片來將徽標整合到 QR 代碼中。這使您能夠以品牌元素個性化 QR 代碼。

運行 C# 中的 QR 代碼生成器應用程式需要哪些步驟?

在 C# 中設置和自定義 QR 代碼生成器應用程式後,只需在 Visual Studio 中運行應用程式,生成 QR 代碼,並使用提供的選項將其保存為您想要的格式。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担產品测测试,產品開發和研究的责任時,Jordi 為持续的產品改進增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我