C# QR Code 生成器 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 Code 生成器 Library in C

今天就使用IronQR開始專案,免費試用。

第一步:
green arrow pointer


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

Install-Package IronQR

IronQR: C# QR 程式庫

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

IronQR 的獨特之處在於其高級功能,包括 讀取 QR 碼生成 QR 碼、支持多種圖像格式,以及像調整大小、樣式和向 QR 碼新增商標等自訂選項。

IronQR 的一些主要功能

IronQR 的功能超出基本的 QR 碼生成,提供了旨在滿足各種 QR 碼相關任務的多項功能。 讓我們瀏覽這些功能,並檢查它們的範例程式碼,您將能夠將其整合到任何型別的 .NET 應用程式範本中,如控制台應用程式。

讀取 QR 碼

IronQR 精於解碼 QR 碼,為使用者提供了一種簡單的方法來存取嵌入在 QR 碼中的資訊。 您可以快速準確地從 QR 碼中提取資料,從簡單的 URL 到複雜的嵌入資訊。

: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 Code 生成器,請仔細按照以下步驟操作。 本指南將引導您設置 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 Code 生成器

    3.1 標題頭

    生成 QR 碼

    啟動 QR Code 生成器應用程式後,使用者立即會看到一個標題為"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.Color 格式,並根據選擇更新 QR 碼的前景或背景顏色。 它還會更新 UI,以反映新的顏色選擇:

    :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提供的特定程式碼行,以使用您購買的授權來激活該程式庫。

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

    IronQR允許您通過其顏色自訂功能來設計特定顏色的QR碼。您可以通過整合到應用程式中的顏色選擇對話框為QR碼前景和背景選擇顏色。

    在Visual Studio中安裝QR碼程式庫的流程是什麼?

    要在Visual Studio中安裝像IronQR這樣的QR碼程式庫,請使用NuGet套件管理器。搜尋'IronQR'並點擊'安裝'將其新增到您的專案中。或者,使用套件管理器控制台的命令'Install-Package IronQR'。

    Curtis Chau
    技術作家

    Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

    除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

    準備好開始了嗎?
    Nuget 下載 70,398 | 版本: 2026.7 剛剛發布
    Still Scrolling Icon

    還在滾動?

    想要快速證明嗎? PM > Install-Package IronQR
    執行一個範例 觀看您的URL變成QR碼。