C# 二維碼產生器應用程式

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

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

在 C# 中安裝二維碼產生器庫

立即開始在您的項目中使用 IronQR 並免費試用。

第一步:
green arrow pointer


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

Install-Package IronQR

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 擅長解碼二維碼,為使用者提供了一種直接存取二維碼中嵌入資訊的方法。 您可以快速且準確地從二維碼中提取數據,從簡單的網址到複雜的嵌入式資訊。

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

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

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

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

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

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

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

IronQr.License.LicenseKey = "License-Key"

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

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

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

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

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

這個過程首先引入必要的命名空間:IronQr 和 IronSoftware.Drawing,其中特別提到了 IronSoftware.Drawing 命名空間中的 Color 來處理影像操作。

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

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

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

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

自訂二維碼讀取模式選項

IronQR 提供不同的二維碼讀取模式,可滿足各種不同的需求。

-混合掃描模式:兼顧速度和準確性,適用於不清晰或部分隱藏的二維碼。 -機器學習 (ML) 掃描模式:採用先進技術讀取損壞或難以讀取的二維碼,非常適合難以檢測的場景。 -基本掃描模式:最簡單快速的方式,可掃描清晰明了的二維碼。

: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

讀取高級二維碼

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

: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 庫建立二維碼產生器,請仔細按照下列步驟操作。 本指南將引導您完成設定 Windows 窗體應用程式、安裝 IronQR 程式庫、編寫產生二維碼的程式碼以及了解輸出結果的過程。

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

  1. 首先在您的電腦上啟動 Visual Studio。
  2. 點選"建立新項目"按鈕。
  3. 選擇"Windows 窗體應用程式"作為專案類型。 請務必選擇 C# 作為程式語言。

    Windows 窗體應用程式

  4. 輸入項目名稱並選擇儲存位置。 然後在下一個畫面上,選擇 .NET 框架。 然後點選"創建"

    專案配置

步驟 2:安裝 IronQR 庫

現在是時候在專案中安裝 IronQR 庫了。 您可以透過不同的方法安裝 IronQR 庫。

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

  1. 在解決方案資源管理器中以滑鼠右鍵按一下您的項目,然後選擇"管理 NuGet 套件"
  2. 在搜尋框中輸入IronQR並按Enter 鍵管理 NuGet 套件
  3. 在清單中找到IronQR ,然後點選旁邊的"安裝"

    安裝 IronQR

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

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

    步驟三:設計前端

    QR Code Generator

    3.1 標題頁眉

    產生二維碼

    啟動二維碼產生器應用程式後,用戶會立即看到一個醒目的標題"QR Generator IronQR",字體粗體且權威。

    3.2 輸入部分

    二維碼文字輸入

    使用者可以輸入他們想要編碼到二維碼中的資料。

    標誌選擇

    選擇標誌

    "選擇徽標"區域允許進行更進階的自訂設定。 用戶可以上傳一個徽標,該徽標將嵌入到二維碼中。

    色彩配置

    背景顏色

    顏色選擇按鈕可讓使用者自訂二維碼的調色板。

    3.3 樣式參數

    造型

    尺寸設定

    允許使用者指定二維碼的整體尺寸。

    邊距設定

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

    3.4 輸出預覽

    提供產生的二維碼的即時預覽。

    QR 圖碼輸出

    3.5 操作按鈕

    產生二維碼

    觸發二維碼產生過程。

    C# 中的二維碼

    儲存二維碼

    開啟儲存對話框,用於儲存二維碼。

    省下

    重設表單

    清除之前的所有輸入和選擇。

    重置

    第四步:編寫後端邏輯

    4.1 設定和初始化

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

    請將&quot;YOUR_LICENSE_KEY&quot;替換為您的實際許可證密鑰。

    4.3 目錄管理

    檢查或建立必要的目錄。

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

    QR_Generator 類別建構子中定義了 QR 碼目錄的路徑,即 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 格式,並根據選擇更新二維碼的前景色或背景色。 它還會更新使用者介面以反映新的顏色選擇:

    :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 二維碼生成

    包含根據使用者輸入產生二維碼的邏輯。

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

    負責保存產生的二維碼。

    :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:運行應用程式

    應用程式運行時,主視窗會顯示為分為輸入、樣式、輸出和操作等部分。 依照使用者介面輸入數據,自訂二維碼,並根據需要產生和儲存二維碼。

    結論

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

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

    常見問題解答

    如何在 C# 中建立 QR 代碼產生器應用程式?

    若要在 C# 中建立 QR 碼產生器應用程式,您可以使用 IronQR 函式庫。首先在 Visual Studio 中建立 Windows Forms 應用程式,透過 NuGet 安裝 IronQR,然後設計您應用程式的前端。使用 IronQR 的功能實作 QR 碼產生邏輯,例如顏色選擇和標誌嵌入。

    使用 .NET QR code library 有什麼好處?

    IronQR 之類的 .NET QR code library 可提供先進的功能,例如讀取 QR code 的高準確度、產生 QR code 的客製化選項,以及支援各種 .NET 環境。它還可以調整 QR 碼的大小和樣式。

    在 C# 中生成 QR 碼時,如何處理錯誤?

    在 C# 中,您可以使用 try-catch 區塊實作適當的錯誤處理機制,以處理 QR 代碼產生過程中的錯誤。IronQR 可促進順暢的錯誤管理,確保有效處理 QR 碼建立過程中的任何問題。

    我可以使用 QR 代碼庫將標誌嵌入 QR 代碼嗎?

    是的,您可以使用 IronQR 函式庫將標誌嵌入 QR 碼中。此功能可讓您在設計中加入自訂的標誌,以加強 QR 代碼的品牌形象。

    如何儲存 C# 應用程式中產生的 QR 碼?

    您可以使用 IronQR 指定儲存目錄的功能,儲存在 C# 應用程式中產生的 QR 碼。這可讓您在應用程式中有效地管理和儲存所產生的 QR 代碼。

    設定 QR code library 的授權金鑰需要哪些步驟?

    若要設定 IronQR 的授權金鑰,您需要在應用程式中加入授權程式碼。這通常需要加入 IronQR 提供的特定程式碼行,以使用您購買的授權來啟動函式庫。

    如何在我的 C# 應用程式中使用特定顏色的 QR 代碼樣式?

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

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

    若要在 Visual Studio 中安裝 IronQR 之類的 QR code library,請使用 NuGet Package Manager。搜索 "IronQR「,然後點擊 」Install "將其添加到您的專案中。或者,使用套件管理員控制台,執行指令「Install-Package IronQR」。

    Curtis Chau
    技術作家

    Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

    除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

    準備好開始了嗎?
    Nuget 下載 51,390 | Version: 2025.11 剛發表