C# QR 碼生成器 Application

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

歡迎閱讀本指南,了解如何使用 C# 建立 QR 碼! QR 碼和 .NET BARCODE DLL 已成為快速且高效分享資訊的熱門方式。 無論您是開發應用程式、管理網站,還是只是想找個簡潔的方式分享連結,這些程式碼都將極具實用價值。 在本指南中,我們將示範如何使用 IronQR 高效生成 QR 碼,確保您能根據自身需求生成客製化的 QR 碼。 此函式庫讓任何使用 C# 的開發者都能輕鬆建立 QR 碼,無需處理複雜的邏輯。 我們將逐步引導您,確保您具備開始所需的一切資源。 無論您是想為應用程式新增 QR 碼產生功能,還是單純好奇其運作原理,您來對地方了。 讓我們開始吧。

Install QR 碼生成器 Library in C

立即透過免費試用,在您的專案中開始使用 IronQR。

第一步:
green arrow pointer


開始之前,我們需要安裝 IronQR NuGet 套件。

Install-Package IronQR

IronQR:C# QR 程式庫

IronQR 是一款 C# QR 碼程式庫,用於將 QR 碼功能整合至 .NET 應用程式中。 IronQR 支援廣泛的 .NET 版本與專案類型,包括 C#、VB.NET、F#、.NET Core、.NET Standard、.NET Framework 等,確保與 Windows、Linux、macOS、iOS 及 Android 等各種開發環境相容。

IronQR 憑藉其先進功能脫穎而出,包括讀取生成 QR 碼的能力、支援多種圖像格式,以及可自訂 QR 碼大小、樣式和添加標誌等選項。

IronQR 的部分關鍵功能

IronQR 的功能不僅限於基本的 QR 碼生成,更提供多項專為處理各類 QR 碼相關任務而設計的功能。 讓我們逐一檢視這些功能,並查看其範例程式碼,您將能將這些程式碼整合至任何類型的 .NET 應用程式範本中,例如控制台應用程式。

讀取 QR 碼

IronQR 在解碼 QR 碼方面表現出色,為使用者提供一種簡便的方式來存取 QR 碼中嵌入的資訊。 您可以快速且精確地從 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

流程首先需導入必要的命名空間:IronQrIronSoftware.Drawing,並特別提及來自 IronSoftware.Drawing 命名空間的 Color,以處理影像操作。

在深入探討 QR 碼讀取流程之前,務必先將您的授權金鑰指派至 IronQr.License.LicenseKey,以啟用軟體。 接著,程式碼會使用 AnyBitmap.FromFile("QRCode.png") 從檔案中載入 QR 碼圖像。

載入圖片後,下一步是將其準備好以供 QR 碼偵測。 此準備工作是透過建立一個 QrImageInput 物件來完成,該物件用作圖片的容器。

此功能的核心在於 QrReader 類別,該類別經實例化後,將用於執行 QR 碼讀取操作。 讀者會分析已準備好的圖像,搜尋其中所含的任何 QR 碼。 此操作的結果是一組 QrResult 物件,每個物件代表影像中偵測到的 QR 碼。

為了存取並利用 QR 碼中編碼的資料,程式會使用 foreach 迴圈遍歷結果集合。每個 QrResult 物件都包含諸如 QR 碼值等屬性,這些屬性可供存取並顯示。

自訂 QR 碼讀取模式選項

IronQR 提供多種讀取 QR 碼的模式,使其能靈活滿足各種需求。

  • 混合掃描模式:在速度與準確性之間取得平衡,適用於圖像模糊或部分被遮擋的 QR 碼。
  • 機器學習 (ML) 掃描模式:運用先進技術讀取受損或難以辨識的 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 Forms 應用程式"作為專案類型。 請務必選擇 C# 作為程式語言。

    Windows Forms 應用程式

  4. 輸入專案名稱並選擇儲存位置。 接著在下一畫面中,請選擇 .NET Framework。 接著點擊"建立"

    專案配置

步驟 2:安裝 IronQR 程式庫

現在是時候在專案中安裝 IronQR程式庫了。 您可以透過多種方式安裝 IronQR程式庫。

請使用 NuGet 套件管理員進行安裝

  1. 在"解決方案總覽"中右鍵點擊您的專案,然後選擇"管理 NuGet 套件"。
  2. 在搜尋框中輸入 IronQR 並按下 Enter 鍵管理 NuGet 套件
  3. 在清單中找到 IronQR,並點擊其旁的"安裝"。

    安裝 IronQR

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

  • 前往"工具">"NuGet 套件管理員">"套件管理員主控台"
    NuGet 套件管理員
  • 輸入 Install-Package IronQr 並按下 Enter 鍵。
  • 安裝 IronQR

    步驟 3:設計前端

    QR 碼生成器

    3.1 標題欄

    產生 QR 碼

    啟動 QR 碼產生器應用程式後,使用者會立即看到一個醒目的標題"QR Generator IronQR",採用粗體且具權威感的字型呈現。

    3.2 輸入區段

    QR 碼文字輸入

    使用者可將欲編碼的資料輸入至其 QR 碼中。

    標誌選定

    選擇標誌

    "選擇標誌"區域可提供額外的自訂層級。 使用者可上傳一個標誌,該標誌將嵌入 QR 碼中。

    色彩設定

    背景顏色

    色彩選取按鈕讓使用者能自訂 QR 碼的配色方案。

    3.3 樣式參數

    格式規範

    維度設定

    允許使用者指定 QR 碼的整體大小。

    邊距設定

    允許使用者指定 QR 碼周圍的空白區域。

    3.4 輸出預覽

    提供所產生 QR 碼的即時預覽。

    QR 輸出

    3.5 動作按鈕

    產生 QR 碼

    觸發 QR 碼的生成流程。

    C# 中的 QR 碼

    儲存 QR 碼

    開啟儲存對話方塊以儲存 QR 碼。

    節省

    重設表單

    清除所有先前輸入的內容與選項。

    重設

    步驟 4:撰寫後端邏輯

    4.1 設定與初始化

    包含必要的命名空間:IronQrIronSoftware.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

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

    請將 "YOUR_LICENSE_KEY" 替換為您的實際授權金鑰。

    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 Codes"資料夾名稱:

    :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 方法會取用選定的顏色,並透過十六進位字串將其轉換為 IronSoftware.Drawing.Co/lor 格式,並根據選取內容更新 QR 碼的前景色或背景色。 此外,亦更新了使用者介面以反映新的配色方案:

    :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

    4.10 完整程式碼範例

    整合上述所有功能的完整程式碼,可於您專案中連結的範例檔案中找到。

    :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

    步驟 5:執行應用程式

    執行應用程式時,主視窗會以分區形式呈現,包含輸入、樣式、輸出及動作等區塊。 請依照使用者介面輸入資料、自訂您的 QR 碼,並依需求產生及儲存 QR 碼。

    結論

    總而言之,本指南已引導您逐步了解如何在 C# 應用程式中使用 IronQR程式庫生成 QR 碼。 透過逐步解析從在 Visual Studio 中建立專案、整合 IronQR程式庫、設計使用者友善介面,到撰寫後端邏輯的各步驟,我們已展示為您的應用程式新增 QR 碼功能是多麼容易上手。

    對於有興趣進一步探索 IronQR 功能的人士,值得注意的是 IronQR 提供免費用版,讓您輕鬆上手。 若您決定將 IronQR 整合至您的專案中,授權價格自 $999 起,為專業級 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 提供的特定程式碼行,以使用您購買的授權來啟用 IronQR程式庫。

    如何在 C# 應用程式中使用特定顏色來設計 QR 碼?

    IronQR 透過其色彩自訂功能,讓您能使用特定顏色來設計 QR 碼。您可以利用整合至應用程式中的選色對話方塊,為 QR 碼的前景與背景選擇顏色。

    在 Visual Studio 中安裝 QR 碼函式庫的流程為何?

    要在 Visual Studio 中安裝 IronQR 這樣的 QR 碼程式庫,請使用 NuGet 套件管理員。搜尋「IronQR」並點擊「安裝」即可將其加入您的專案。或者,您也可以透過套件管理員控制台執行「Install-Package IronQR」指令。

    Curtis Chau
    技術撰稿人

    Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

    除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

    準備開始了嗎?
    Nuget 下載 67,270 | 版本: 2026.5 just released
    Still Scrolling Icon

    還在往下捲動嗎?

    想要快速確認成果嗎? PM > Install-Package IronQR
    執行範例 觀看您的 URL 轉為 QR 碼。