USING IRONQR

How to Create a QR Code Generator Application In C#

Published May 20, 2024
Share:

Welcome to our guide on creating QR codes using C#! QR codes and .NET barcode DLL have become popular ways to share information quickly and efficiently. Whether you're developing an app, managing a website, or just looking for a neat way to share links, these codes can be incredibly useful. In this guide, we'll demonstrate how to generate QR codes efficiently using IronQR, ensuring you can generate QR code tailored to your needs. This library makes it easy for anyone working with C# to create QR codes without getting into complex logic. We'll walk you through the steps, ensuring you have everything you need to get started. Whether you're looking to add QR code generator functionality to your app or just curious about how it's done, you're in the right place. Let's get started.

How to Create a QR Code Generator In C#

  1. Create a Windows Forms Application in Visual Studio
  2. Install QR Library using NuGet
  3. Design the form frontend elements
  4. Write logic of QR generation5. Run the application and start creating QR codes

IronQR: C# QR Library

IronQR is a C# QR Code library for integrating QR code functionality into .NET applications. IronQR supports a wide range of .NET versions and project types, including C#, VB.NET, F#, .NET Core, .NET Standard, .NET Framework, and more, ensuring compatibility with various development environments such as Windows, Linux, macOS, iOS, and Android.

IronQR distinguishes itself with its advanced features, including the ability to read QR codes and generate QR codes, support for multiple image formats, and customization options like resizing, styling, and adding logos to QR codes.

Some Key Features of IronQR

IronQR extends its functionality beyond basic QR code generation, offering several features designed to accommodate a wide range of QR code-related tasks. Let's get through these features and check their example codes which you will be able to integrate into any type of .NET application template like console app.

Read QR Codes

IronQR excels in decoding QR codes, providing users with a straightforward way to access the information embedded within QR codes. You can quickly and accurately extract data from QR codes, ranging from simple URLs to complex embedded information.

using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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
}
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

We use the following QR for scan:

How to Create a QR Code Generator Application In C#: Figure 1 - QR Code PNG Image File

And we got this output:

How to Create a QR Code Generator Application In C#: Figure 2 - Read QR Code Output

The process starts by incorporating the necessary namespaces, IronQr, and IronSoftware.Drawing, with a specific mention of Color from the IronSoftware.Drawing namespace to handle image manipulations.

Before diving into the QR code reading process, it's essential to activate the software with your license key by assigning it to IronQr.License.LicenseKey. The code then proceeds to load the QR code image from a file using AnyBitmap.FromFile("QRCode.png").

With the image loaded, the next step involves preparing it for QR code detection. This preparation is done by creating a QrImageInput object, which serves as a container for the image.

The core of this feature lies in the QrReader class, which is instantiated and used to perform the QR code reading operation. The reader analyzes the prepared image, qrInput, searching for any QR codes it contains. The result of this operation is a collection of QrResult objects, each representing a detected QR code within the image.

To access and utilize the data encoded in the QR codes, the code iterates over the collection of results using a foreach loop. Each QrResult object contains properties such as the QR code's value, which can be accessed and displayed.

Custom QR Read Mode Options

IronQR gives you different ways to read QR codes from images, making it versatile for various needs. One option is the Mixed Scan Mode, which balances speed and accuracy, useful when QR codes are not clear or are partly hidden.

Another is the Machine Learning (ML) Scan Mode, which uses smart technology to read QR codes that are damaged or not easy to read normally. This mode is great for tough situations where QR codes are hard to detect.

Lastly, there's the Basic Scan Mode, which is the fastest and simplest way to scan clear and straightforward QR codes. It's best when you need quick results and the QR codes are easy to read.

using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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 Color = IronSoftware.Drawing.Color
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)
VB   C#

Read Advance QR Codes

IronQR's advanced QR code reading capabilities are designed to offer a comprehensive and nuanced approach to QR code scanning and decoding. This feature set extends beyond basic QR code reading functionalities, providing a deeper level of interaction and data extraction.

using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
IronQr.License.LicenseKey = "License-Key";
var imageToScan = AnyBitmap.FromFile("QRCode.png");
QrImageInput qrInput = new QrImageInput(imageToScan);
QrReader qrScanner = new QrReader();
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
foreach (QrResult qrResult in scanResults)
{
    Console.WriteLine(qrResult.Value);
    Console.WriteLine(qrResult.Url);
    foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points)
    {
        Console.WriteLine($"{coordinate.X}, {coordinate.Y}");
    }
}
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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 IronQr.Enum
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
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
VB   C#

This is the output when we scan the QR code using IronQR:

How to Create a QR Code Generator Application In C#: Figure 3 - Scan QR Code Output

We use the following QR Code:

How to Create a QR Code Generator Application In C#: Figure 4 - QR Code Input

Each QrResult object provides access to the decoded data (Value), any embedded URLs (Url), and the spatial coordinates (Points) of the QR code within the image.

For each QR code detected, IronQR offers detailed information, including the exact content and any URLs contained within the QR code. Moreover, the library provides the precise coordinates of the QR code's corners in the image (through the Points property).

To create a QR Code generator using the IronQR library of QR codes in a C# application, follow these steps carefully. This guide will take you through setting up a Windows form application, installing the IronQR library, writing the code to generate a QR code, and understanding the output.

Step 1: Create a Windows Application in Visual Studio

  • Start by launching Visual Studio on your computer.
  • Click on the "Create a New Project" button.
  • Select Windows Forms App as the project type. Make sure to choose C# as the language.

    How to Create a QR Code Generator Application In C#: Figure 5 - Windows Forms App

  • Enter a name for your project and select the location to save it. Then on the next screen, select .NET framework. Then click Create.

    How to Create a QR Code Generator Application In C#: Figure 6 - Project Configuration

It'll create and open a Windows forms application in Visual Studio.

Step 2: Install IronQR Library

Now it's time to install the IronQR library in the project. You can install the IronQR library through different methods. Choose one that suits your preference:

Install using NuGet Package Manager

  • Right-click on your project in the Solution Explorer and select Manage NuGet Packages.
  • Type IronQR in the search box and press Enter.

    How to Create a QR Code Generator Application In C#: Figure 7 - Manage NuGet Packages

  • Find IronQR in the list and click Install next to it.

    How to Create a QR Code Generator Application In C#: Figure 8 - Install IronQR

Install using NuGet Package Manager Console

  • Go to Tools > NuGet Package Manager > Package Manager Console.

How to Create a QR Code Generator Application In C#: Figure 9 - NuGet Package Manager

  • Type Install-Package IronQR and press Enter.

How to Create a QR Code Generator Application In C#: Figure 10 - Install IronQR

Step 3: Design Frontend

How to Create a QR Code Generator Application In C#: Figure 11 - QR Code Generator

3.1 Title Header

How to Create a QR Code Generator Application In C#: Figure 12 - Generate a QR Code

Upon launching the QR Code Generator application, users are immediately presented with a striking header titled "QR Generator IronQR," set in a bold and authoritative font. The font, Agency FB, is selected for its clean, modern lines, which convey a sense of efficiency and precision. At a sizeable 48-point font, the title is both prominent and assertive, capturing the user's attention and firmly establishing the application's identity.

3.2 Input Section

Text Input for QR Code

How to Create a QR Code Generator Application In C#: Figure 13 - QR Code Text Input

At the heart of the input section lies a simple yet fundamental component: the text input box. Here, users can enter the data they wish to encode into their QR code. The box is spacious, accommodating a significant amount of text, and is positioned prominently near the top.

Logo Selection

How to Create a QR Code Generator Application In C#: Figure 14 - Select Logo

Below the text input, the "Select Logo" area allows for an additional layer of customization. Users can upload a logo that will be embedded in the QR code, enhancing brand recognition or personalizing the code. The adjacent picture box provides a preview of the selected logo, offering immediate visual feedback.

Color Configuration

How to Create a QR Code Generator Application In C#: Figure 15 - Background Color

Moving to the right, the interface presents options for color selection. Two buttons, one for the QR code's color and another for the background color enable users to customize their QR code's palette. The rich textboxes next to these buttons show the currently selected color.

The thoughtful layout of the input section, with its text, logo, and color options, reflects a clear understanding of user priorities when creating a QR code. It combines functionality with flexibility, allowing users to quickly and efficiently input the necessary information while also offering room for creativity.

3.3 Styling Parameters

How to Create a QR Code Generator Application In C#: Figure 16 - Styling

Dimension Settings

Adjacent to the color customization tools, users will find the input for "Dimensions." This numerical setting is critical as it dictates the overall size of the QR code, ensuring it fits perfectly within the intended display context, whether it's a business card, a flyer, or a digital screen.

Margin Settings

Next to the dimension input, the "Margins" field allows users to specify the white space surrounding the QR code. Margins are more than just an aesthetic choice; they're a functional element that can affect the readability of the QR code by scanners. The application provides a numeric up-down control for users to adjust this parameter easily.

3.4 Output Preview

How to Create a QR Code Generator Application In C#: Figure 17 - QR Output

Once the user initiates the QR code generation, the large picture box on the left side of the form, labeled as "Output," becomes the focal point. It serves as a dynamic display, providing a real-time preview of the generated QR code. This immediate visual feedback is essential for users to verify their design choices and ensure the QR code meets their expectations before saving.

3.5 Action Buttons

Generate QR

How to Create a QR Code Generator Application In C#: Figure 18 - QR Code in C#

The "Generate QR" button is a pivotal control element in the application's interface. Positioned strategically within the form, this button is the catalyst for the QR code creation process. Upon clicking this button, the application takes all the input data and styling parameters defined by the user and commences the generation of a custom QR code.

Save QR Code

How to Create a QR Code Generator Application In C#: Figure 19 - Save

Once a QR code has been generated and is displayed in the output preview area, the "Save QR" button comes into play. When clicked, it opens a save dialog, allowing the user to choose the desired file format and save location.

Reset Form

How to Create a QR Code Generator Application In C#: Figure 20 - Reset

With a single click, this button clears all previous inputs and selections, restoring all settings to their default values. It is an important aspect of the form, offering a quick way to reinitialize the application without manually adjusting each option.

Step 4: Write Backend Logic

4.1 Setup and Initialization

First, the application begins with the inclusion of necessary namespaces: IronQr and IronSoftware.Drawing. These namespaces are essential as they provide the functionalities needed to generate and manipulate QR codes and colors within the application. The custom Color class is defined to facilitate color management in QR code generation, overriding the default System.Drawing.Color to ensure compatibility with IronQR's requirements.

using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
VB   C#

The constructor for the QR_Generator class plays a crucial role in preparing the application for use. It's here that the application's components are initialized, which is a standard step in Windows Forms applications to set up the form's UI elements.

public QR_Generator()
{
    InitializeComponent();
    SetLicenseKey();
    EnsureDirectoryExists(qrCodesDirectory);
}
public QR_Generator()
{
    InitializeComponent();
    SetLicenseKey();
    EnsureDirectoryExists(qrCodesDirectory);
}
'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
'ORIGINAL LINE: public QR_Generator()
Public Sub New()
	InitializeComponent()
	SetLicenseKey()
	EnsureDirectoryExists(qrCodesDirectory)
End Sub
VB   C#

SetLicenseKey: This method is called to apply a valid license key for the IronQR library. The use of a license key is mandatory for commercial applications and to unlock the full capabilities of the IronQR library.

EnsureDirectoryExists: Given the need to save generated QR codes, this method ensures there is a dedicated directory available. It checks if the "QR Codes" directory exists at the application's startup path and creates it if it doesn't.

4.2 License Key Configuration

To ensure that IronQR operates without limitations, a valid license key must be applied. This is accomplished through the SetLicenseKey method, which is a static method designed to configure the library with your purchased or trial license key. The code snippet below illustrates how to set the license key:

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
VB   C#

Replace "YOUR\_LICENSE\_KEY" with the actual license key you obtained from Iron Software. The method is called within the constructor of the QR_Generator class, ensuring that the license is applied as soon as the application starts and before any QR code generation takes place.

4.3 Directory Management

The application uses the EnsureDirectoryExists method to check if the specified directory for storing QR codes exists. If not, it creates the directory. This method takes a string parameter, which is the path of the directory to check or create. Here's how it's implemented:

private static void EnsureDirectoryExists(string path)
{
    if (!System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path);
    }
}
private static void EnsureDirectoryExists(string path)
{
    if (!System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path);
    }
}
Private Shared Sub EnsureDirectoryExists(ByVal path As String)
	If Not System.IO.Directory.Exists(path) Then
		System.IO.Directory.CreateDirectory(path)
	End If
End Sub
VB   C#

This method utilizes the System.IO namespace to interact with the file system. It first checks if the directory at the specified path exists using Directory.Exists. If the directory does not exist (false is returned), it then creates the directory using Directory.CreateDirectory.

The path to the QR codes directory is defined in the QR_Generator class constructor as qrCodesDirectory, which combines the application's startup path with a "QR Codes" folder name:

string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
Dim qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")
VB   C#

4.4 Color Selection

The application provides two buttons on the user interface, each tied to a method for selecting colors: btn\_color\_Click for the QR code color and btn\_background\_Click for the background color. These methods leverage a color dialog box to let the user pick colors.

When a color is selected using the color dialog box, the chosen color is then converted to a hexadecimal string format. This is necessary because the IronQR library requires colors to be specified in hexadecimal format. The conversion is done through the ColorToHex method:

private string ColorToHex(System.Drawing.Color color)
{
    return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
private string ColorToHex(System.Drawing.Color color)
{
    return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
	Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End Function
VB   C#

The UpdateColor method takes the selected color and converts it to the IronSoftware.Drawing.Color format using the hexadecimal string, and updates either the QR code's foreground or background color depending on the selection. It also updates the UI to reflect the new color choice:

private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
    if (select_color.ShowDialog() == DialogResult.OK)
    {
        var hexColor = ColorToHex(select_color.Color);
        targetColor = new Color(hexColor);
        display.BackColor = select_color.Color;
    }
}
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
    if (select_color.ShowDialog() == DialogResult.OK)
    {
        var hexColor = ColorToHex(select_color.Color);
        targetColor = new Color(hexColor);
        display.BackColor = select_color.Color;
    }
}
Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
	If select_color.ShowDialog() = DialogResult.OK Then
		Dim hexColor = ColorToHex(select_color.Color)
		targetColor = New Color(hexColor)
		display.BackColor = select_color.Color
	End If
End Sub
VB   C#

The application includes a button (btn_logo_Click) that, when clicked, opens a file dialog allowing the user to select an image file to be used as the logo. This functionality is critical for businesses or individuals looking to brand their QR codes. Here's how the logo selection and integration process is handled:

private void btn_logo_Click(object sender, EventArgs e)
{
    if (select_logo.ShowDialog() == DialogResult.OK)
    {
        try
        {
            logoBmp = new AnyBitmap(select_logo.FileName);
            selected_logo.Image = Image.FromFile(select_logo.FileName);
        }
        catch (Exception ex)
        {
            ShowError("An error occurred while loading the logo", ex.Message);
        }
    }
}
private void btn_logo_Click(object sender, EventArgs e)
{
    if (select_logo.ShowDialog() == DialogResult.OK)
    {
        try
        {
            logoBmp = new AnyBitmap(select_logo.FileName);
            selected_logo.Image = Image.FromFile(select_logo.FileName);
        }
        catch (Exception ex)
        {
            ShowError("An error occurred while loading the logo", ex.Message);
        }
    }
}
Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
	If select_logo.ShowDialog() = DialogResult.OK Then
		Try
			logoBmp = New AnyBitmap(select_logo.FileName)
			selected_logo.Image = Image.FromFile(select_logo.FileName)
		Catch ex As Exception
			ShowError("An error occurred while loading the logo", ex.Message)
		End Try
	End If
End Sub
VB   C#

Upon successfully selecting an image, the application attempts to load it and display a preview. The AnyBitmap object, logoBmp, is then set with the selected image, which the QR generation logic later uses.

4.6 QR Code Generation

The generation process begins when the user clicks the "Generate" button, which is linked to the btn\_generate\_Click method. This method acts as a trigger, calling the GenerateQRCode function where the actual generation logic resides.

private void btn_generate_Click(object sender, EventArgs e)
{
    GenerateQRCode();
}
private void btn_generate_Click(object sender, EventArgs e)
{
    GenerateQRCode();
}
Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
	GenerateQRCode()
End Sub
VB   C#

Within the GenerateQRCode method, the application constructs a QR code based on the specified parameters, including the input text and style options. The method encapsulates the creation of a QR code, applying the selected colors, dimensions, margins, and optionally, a logo.

private void GenerateQRCode()
{
    try
    {
        var options = new QrOptions(QrErrorCorrectionLevel.High);
        var myQr = QrWriter.Write(txt_QR.Text, options);
        var style = CreateStyleOptions();
        var qrImage = myQr.Save(style);
        var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
        var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
        qrImage.SaveAs(fullPath);
        pictureBox.Image = Image.FromFile(fullPath);
    }
    catch (Exception ex)
    {
        ShowError("An error occurred during QR code generation or saving", ex.Message);
    }
}
private void GenerateQRCode()
{
    try
    {
        var options = new QrOptions(QrErrorCorrectionLevel.High);
        var myQr = QrWriter.Write(txt_QR.Text, options);
        var style = CreateStyleOptions();
        var qrImage = myQr.Save(style);
        var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
        var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
        qrImage.SaveAs(fullPath);
        pictureBox.Image = Image.FromFile(fullPath);
    }
    catch (Exception ex)
    {
        ShowError("An error occurred during QR code generation or saving", ex.Message);
    }
}
Private Sub GenerateQRCode()
	Try
		Dim options = New QrOptions(QrErrorCorrectionLevel.High)
		Dim myQr = QrWriter.Write(txt_QR.Text, options)
		Dim style = CreateStyleOptions()
		Dim qrImage = myQr.Save(style)
		Dim fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png"
		Dim fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName)
		qrImage.SaveAs(fullPath)
		pictureBox.Image = Image.FromFile(fullPath)
	Catch ex As Exception
		ShowError("An error occurred during QR code generation or saving", ex.Message)
	End Try
End Sub
VB   C#

The QrOptions object defines the error correction level, enhancing the QR code's resilience to damage or obscuration. The CreateStyleOptions method generates a QrStyleOptions object, which includes the user's custom settings like colors, dimensions, and the logo. Here's the method in detail:

private QrStyleOptions CreateStyleOptions()
{
    return new QrStyleOptions
    {
        BackgroundColor = bgColor,
        Color = color,
        Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
        Margins = Convert.ToInt32(txt_margin.Value),
        Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
    };
}
private QrStyleOptions CreateStyleOptions()
{
    return new QrStyleOptions
    {
        BackgroundColor = bgColor,
        Color = color,
        Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
        Margins = Convert.ToInt32(txt_margin.Value),
        Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
    };
}
Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
	Return New QrStyleOptions With {
		.BackgroundColor = bgColor,
		.Color = color,
		.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
		.Margins = Convert.ToInt32(txt_margin.Value),
		.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
			.Bitmap = logoBmp,
			.Width = 50,
			.Height = 50,
			.CornerRadius = 5
		}, Nothing)
	}
End Function
VB   C#

This method creates a QrStyleOptions object, which is then used by the QR code generation logic to apply the user's preferences. The options include:

  • BackgroundColor and Color: These properties set the background and foreground colors of the QR code, allowing for a personalized look that can match branding or aesthetic preferences.
  • Dimensions: This property determines the size of the QR code, offering flexibility in how the QR code fits within different contexts or mediums.
  • Margins: This property sets the margin size around the QR code, ensuring it is isolated from surrounding elements, which can be crucial for scalability.
  • Logo: If the user has chosen to include a logo, it's configured here with specific dimensions and a corner radius for a polished look.

4.7 Saving the QR Code

The saving functionality is triggered by the "Save" button, which is linked to the btn\_save\_Click method. This method calls SaveQRCode, which implements the saving logic. The process includes displaying a save file dialog, allowing the user to choose the file format and location for saving the QR code.

private void btn_save_Click(object sender, EventArgs e)
{
    SaveQRCode();
}
private void SaveQRCode()
{
    if (pictureBox.Image == null)
    {
        MessageBox.Show("There is no QR code to save.", "Error");
        return;
    }
    saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
    saveFileDialog.Title = "Save QR Code";
    saveFileDialog.FileName = "QRCode";
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        try
        {
            pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
            MessageBox.Show("QR Code has been saved!", "Success");
        }
        catch (Exception ex)
        {
            ShowError("An error occurred while saving the QR code", ex.Message);
        }
    }
}
private void btn_save_Click(object sender, EventArgs e)
{
    SaveQRCode();
}
private void SaveQRCode()
{
    if (pictureBox.Image == null)
    {
        MessageBox.Show("There is no QR code to save.", "Error");
        return;
    }
    saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
    saveFileDialog.Title = "Save QR Code";
    saveFileDialog.FileName = "QRCode";
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        try
        {
            pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
            MessageBox.Show("QR Code has been saved!", "Success");
        }
        catch (Exception ex)
        {
            ShowError("An error occurred while saving the QR code", ex.Message);
        }
    }
}
Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
	SaveQRCode()
End Sub
Private Sub SaveQRCode()
	If pictureBox.Image Is Nothing Then
		MessageBox.Show("There is no QR code to save.", "Error")
		Return
	End If
	saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
	saveFileDialog.Title = "Save QR Code"
	saveFileDialog.FileName = "QRCode"
	If saveFileDialog.ShowDialog() = DialogResult.OK Then
		Try
			pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
			MessageBox.Show("QR Code has been saved!", "Success")
		Catch ex As Exception
			ShowError("An error occurred while saving the QR code", ex.Message)
		End Try
	End If
End Sub
VB   C#

This method checks if there is a generated QR code available. If so, it presents the user with options to save the file in PNG or JPEG format. The DetermineImageFormat function ensures that the image is saved in the correct format based on the file extension chosen by the user.

private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
    return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
    return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}
Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
	Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
End Function
VB   C#

This flexibility allows users to choose the format that best suits their needs, whether prioritizing quality (PNG) or file size (JPEG).

4.8 Resetting the Application

The reset functionality is linked to a "Reset" button, which invokes the btn\_reset\_Click method. This method, in turn, calls ResetFields, a function designed to clear all user inputs and restore default values for all settings, including text fields, color selections, and the selected logo.

private void btn_reset_Click(object sender, EventArgs e)
{
    ResetFields();
}
private void ResetFields()
{
    txt_QR.Text = string.Empty;
    txt_dimension.Value = 200;
    txt_margin.Value = 0;
    bgColor = Color.White;
    color = Color.Black;
    txt_selected_color.BackColor = System.Drawing.Color.White;
    txt_selected_bgcolor.BackColor = System.Drawing.Color.Black;
    logoBmp = null;
    selected_logo.Image = null;
    pictureBox.Image = null;
}
private void btn_reset_Click(object sender, EventArgs e)
{
    ResetFields();
}
private void ResetFields()
{
    txt_QR.Text = string.Empty;
    txt_dimension.Value = 200;
    txt_margin.Value = 0;
    bgColor = Color.White;
    color = Color.Black;
    txt_selected_color.BackColor = System.Drawing.Color.White;
    txt_selected_bgcolor.BackColor = System.Drawing.Color.Black;
    logoBmp = null;
    selected_logo.Image = null;
    pictureBox.Image = null;
}
Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
	ResetFields()
End Sub
Private Sub ResetFields()
	txt_QR.Text = String.Empty
	txt_dimension.Value = 200
	txt_margin.Value = 0
	bgColor = Color.White
	color = Color.Black
	txt_selected_color.BackColor = System.Drawing.Color.White
	txt_selected_bgcolor.BackColor = System.Drawing.Color.Black
	logoBmp = Nothing
	selected_logo.Image = Nothing
	pictureBox.Image = Nothing
End Sub
VB   C#

This method resets each component involved in QR code generation. For example, it clears the QR code text, sets the dimensions and margins to default values, and removes any selected colors or logos.

4.9 Error Handling

The application uses the ShowError method to display error messages in a user-friendly manner. This method takes two parameters: a title and a message, which provide context about the error to the user. Here's how it's implemented:

private static void ShowError(string title, string message)
{
    MessageBox.Show($"{title}: {message}", "Error");
}
private static void ShowError(string title, string message)
{
    MessageBox.Show($"{title}: {message}", "Error");
}
Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
	MessageBox.Show($"{title}: {message}", "Error")
End Sub
VB   C#

This method is utilized across different parts of the application to ensure that when an error occurs, the user is promptly informed with a clear and concise message. For example, if an error happens while loading the logo or during the QR code generation process, the application calls ShowError to display details about the issue.

4.10 Complete Code Example

Here is the full code which will help you to understand the code much more easily:

using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
namespace IronQR_QR_Generator_WinForms
{
    public partial class QR_Generator : Form
    {
        string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
        Color bgColor = Color.White;
        Color color = Color.Black;
        AnyBitmap? logoBmp = null;
        public QR_Generator()
        {
            InitializeComponent();
            SetLicenseKey();
            EnsureDirectoryExists(qrCodesDirectory);
        }
        private static void SetLicenseKey()
        {
            IronQr.License.LicenseKey = "License-Key";
        }
        private static void EnsureDirectoryExists(string path)
        {
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
        }
        private void btn_color_Click(object sender, EventArgs e)
        {
            UpdateColor(ref color, txt_selected_color, false);
        }
        private void btn_background_Click(object sender, EventArgs e)
        {
            UpdateColor(ref bgColor, txt_selected_bgcolor, true);
        }
        private string ColorToHex(System.Drawing.Color color)
        {
            return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
        }
        private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
        {
            if (select_color.ShowDialog() == DialogResult.OK)
            {
                var hexColor = ColorToHex(select_color.Color);
                targetColor = new Color(hexColor);
                display.BackColor = select_color.Color;
            }
        }
        private void btn_logo_Click(object sender, EventArgs e)
        {
            if (select_logo.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    logoBmp = new AnyBitmap(select_logo.FileName);
                    selected_logo.Image = Image.FromFile(select_logo.FileName);
                }
                catch (Exception ex)
                {
                    ShowError("An error occurred while loading the logo", ex.Message);
                }
            }
        }
        private void btn_generate_Click(object sender, EventArgs e)
        {
            GenerateQRCode();
        }
        private void GenerateQRCode()
        {
            try
            {
                var options = new QrOptions(QrErrorCorrectionLevel.High);
                var myQr = QrWriter.Write(txt_QR.Text, options);
                var style = CreateStyleOptions();
                var qrImage = myQr.Save(style);
                var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
                var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
                qrImage.SaveAs(fullPath);
                pictureBox.Image = Image.FromFile(fullPath);
            }
            catch (Exception ex)
            {
                ShowError("An error occurred during QR code generation or saving", ex.Message);
            }
        }
        private QrStyleOptions CreateStyleOptions()
        {
            return new QrStyleOptions
            {
                BackgroundColor = bgColor,
                Color = color,
                Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
                Margins = Convert.ToInt32(txt_margin.Value),
                Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
            };
        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            SaveQRCode();
        }
        private void SaveQRCode()
        {
            if (pictureBox.Image == null)
            {
                MessageBox.Show("There is no QR code to save.", "Error");
                return;
            }
            saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
            saveFileDialog.Title = "Save QR Code";
            saveFileDialog.FileName = "QRCode";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
                    MessageBox.Show("QR Code has been saved!", "Success");
                }
                catch (Exception ex)
                {
                    ShowError("An error occurred while saving the QR code", ex.Message);
                }
            }
        }
        private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
        {
            return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
        }
        private void btn_reset_Click(object sender, EventArgs e)
        {
            ResetFields();
        }
        private void ResetFields()
        {
            txt_QR.Text = string.Empty;
            txt_dimension.Value = 200;
            txt_margin.Value = 0;
            bgColor = Color.White;
            color = Color.Black;
            txt_selected_color.BackColor = bgColor;
            txt_selected_bgcolor.BackColor = color;
            logoBmp = null;
            selected_logo.Image = null;
            pictureBox.Image = null;
        }
        private static void ShowError(string title, string message)
        {
            MessageBox.Show($"{title}: {message}", "Error");
        }
    }
}
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
namespace IronQR_QR_Generator_WinForms
{
    public partial class QR_Generator : Form
    {
        string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
        Color bgColor = Color.White;
        Color color = Color.Black;
        AnyBitmap? logoBmp = null;
        public QR_Generator()
        {
            InitializeComponent();
            SetLicenseKey();
            EnsureDirectoryExists(qrCodesDirectory);
        }
        private static void SetLicenseKey()
        {
            IronQr.License.LicenseKey = "License-Key";
        }
        private static void EnsureDirectoryExists(string path)
        {
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
        }
        private void btn_color_Click(object sender, EventArgs e)
        {
            UpdateColor(ref color, txt_selected_color, false);
        }
        private void btn_background_Click(object sender, EventArgs e)
        {
            UpdateColor(ref bgColor, txt_selected_bgcolor, true);
        }
        private string ColorToHex(System.Drawing.Color color)
        {
            return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
        }
        private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
        {
            if (select_color.ShowDialog() == DialogResult.OK)
            {
                var hexColor = ColorToHex(select_color.Color);
                targetColor = new Color(hexColor);
                display.BackColor = select_color.Color;
            }
        }
        private void btn_logo_Click(object sender, EventArgs e)
        {
            if (select_logo.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    logoBmp = new AnyBitmap(select_logo.FileName);
                    selected_logo.Image = Image.FromFile(select_logo.FileName);
                }
                catch (Exception ex)
                {
                    ShowError("An error occurred while loading the logo", ex.Message);
                }
            }
        }
        private void btn_generate_Click(object sender, EventArgs e)
        {
            GenerateQRCode();
        }
        private void GenerateQRCode()
        {
            try
            {
                var options = new QrOptions(QrErrorCorrectionLevel.High);
                var myQr = QrWriter.Write(txt_QR.Text, options);
                var style = CreateStyleOptions();
                var qrImage = myQr.Save(style);
                var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
                var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
                qrImage.SaveAs(fullPath);
                pictureBox.Image = Image.FromFile(fullPath);
            }
            catch (Exception ex)
            {
                ShowError("An error occurred during QR code generation or saving", ex.Message);
            }
        }
        private QrStyleOptions CreateStyleOptions()
        {
            return new QrStyleOptions
            {
                BackgroundColor = bgColor,
                Color = color,
                Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
                Margins = Convert.ToInt32(txt_margin.Value),
                Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
            };
        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            SaveQRCode();
        }
        private void SaveQRCode()
        {
            if (pictureBox.Image == null)
            {
                MessageBox.Show("There is no QR code to save.", "Error");
                return;
            }
            saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
            saveFileDialog.Title = "Save QR Code";
            saveFileDialog.FileName = "QRCode";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
                    MessageBox.Show("QR Code has been saved!", "Success");
                }
                catch (Exception ex)
                {
                    ShowError("An error occurred while saving the QR code", ex.Message);
                }
            }
        }
        private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
        {
            return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
        }
        private void btn_reset_Click(object sender, EventArgs e)
        {
            ResetFields();
        }
        private void ResetFields()
        {
            txt_QR.Text = string.Empty;
            txt_dimension.Value = 200;
            txt_margin.Value = 0;
            bgColor = Color.White;
            color = Color.Black;
            txt_selected_color.BackColor = bgColor;
            txt_selected_bgcolor.BackColor = color;
            logoBmp = null;
            selected_logo.Image = null;
            pictureBox.Image = null;
        }
        private static void ShowError(string title, string message)
        {
            MessageBox.Show($"{title}: {message}", "Error");
        }
    }
}
Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
Namespace IronQR_QR_Generator_WinForms
	Partial Public Class QR_Generator
		Inherits Form

		Private qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")
		Private bgColor As Color = Color.White
		Private color As Color = Color.Black
		Private logoBmp? As AnyBitmap = Nothing
		Public Sub New()
			InitializeComponent()
			SetLicenseKey()
			EnsureDirectoryExists(qrCodesDirectory)
		End Sub
		Private Shared Sub SetLicenseKey()
			IronQr.License.LicenseKey = "License-Key"
		End Sub
		Private Shared Sub EnsureDirectoryExists(ByVal path As String)
			If Not System.IO.Directory.Exists(path) Then
				System.IO.Directory.CreateDirectory(path)
			End If
		End Sub
		Private Sub btn_color_Click(ByVal sender As Object, ByVal e As EventArgs)
			UpdateColor(color, txt_selected_color, False)
		End Sub
		Private Sub btn_background_Click(ByVal sender As Object, ByVal e As EventArgs)
			UpdateColor(bgColor, txt_selected_bgcolor, True)
		End Sub
		Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
			Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
		End Function
		Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
			If select_color.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
				Dim hexColor = ColorToHex(select_color.Color)
				targetColor = New Color(hexColor)
				display.BackColor = select_color.Color
			End If
		End Sub
		Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
			If select_logo.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
				Try
					logoBmp = New AnyBitmap(select_logo.FileName)
					selected_logo.Image = Image.FromFile(select_logo.FileName)
				Catch ex As Exception
					ShowError("An error occurred while loading the logo", ex.Message)
				End Try
			End If
		End Sub
		Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
			GenerateQRCode()
		End Sub
		Private Sub GenerateQRCode()
			Try
				Dim options = New QrOptions(QrErrorCorrectionLevel.High)
				Dim myQr = QrWriter.Write(txt_QR.Text, options)
				Dim style = CreateStyleOptions()
				Dim qrImage = myQr.Save(style)
				Dim fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png"
				Dim fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName)
				qrImage.SaveAs(fullPath)
				pictureBox.Image = Image.FromFile(fullPath)
			Catch ex As Exception
				ShowError("An error occurred during QR code generation or saving", ex.Message)
			End Try
		End Sub
		Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
			Return New QrStyleOptions With {
				.BackgroundColor = bgColor,
				.Color = color,
				.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
				.Margins = Convert.ToInt32(txt_margin.Value),
				.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
					.Bitmap = logoBmp,
					.Width = 50,
					.Height = 50,
					.CornerRadius = 5
				}, Nothing)
			}
		End Function
		Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
			SaveQRCode()
		End Sub
		Private Sub SaveQRCode()
			If pictureBox.Image Is Nothing Then
				MessageBox.Show("There is no QR code to save.", "Error")
				Return
			End If
			saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
			saveFileDialog.Title = "Save QR Code"
			saveFileDialog.FileName = "QRCode"
			If saveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
				Try
					pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
					MessageBox.Show("QR Code has been saved!", "Success")
				Catch ex As Exception
					ShowError("An error occurred while saving the QR code", ex.Message)
				End Try
			End If
		End Sub
		Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
			Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
		End Function
		Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
			ResetFields()
		End Sub
		Private Sub ResetFields()
			txt_QR.Text = String.Empty
			txt_dimension.Value = 200
			txt_margin.Value = 0
			bgColor = Color.White
			color = Color.Black
			txt_selected_color.BackColor = bgColor
			txt_selected_bgcolor.BackColor = color
			logoBmp = Nothing
			selected_logo.Image = Nothing
			pictureBox.Image = Nothing
		End Sub
		Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
			MessageBox.Show($"{title}: {message}", "Error")
		End Sub
	End Class
End Namespace
VB   C#

Step 5: Run Application

When the application is executed, the main window appears as showcased in the provided image. The layout is neatly organized into sections for input, styling, output, and actions.

How to Create a QR Code Generator Application In C#: Figure 21 - Application Output

The first step in the process involves entering data into the "Input QR Text" field. This data will form the content of the QR code, such as a URL or textual information. Next, to personalize the QR code, we select a logo by clicking the "Select Logo" button. Upon selection, the logo is visibly placed in the preview box adjacent to the button, confirming its incorporation into the QR code design.

How to Create a QR Code Generator Application In C#: Figure 22 - Logo

Following the logo selection, we choose the QR code's foreground and background colors. After clicking the respective buttons, the chosen colors are reflected in the color display boxes next to each button, giving us immediate visual confirmation of our choices.

How to Create a QR Code Generator Application In C#: Figure 23 - Color Selection

For this particular QR code, we set the dimensions to 500, ensuring the code is of a size suitable for our needs, and adjusted the margins to 20, which provides a buffer around the QR code to prevent scanning issues.

How to Create a QR Code Generator Application In C#: Figure 24 - Dimensions

With all inputs and styling options set, we proceed to generate the QR code by clicking the "Generate QR" button. The application processes our inputs and displays the freshly created QR code in the output picture box.

How to Create a QR Code Generator Application In C#: Figure 25 - Reading QR Codes Output

To save the generated QR code, we simply click the "Save QR" button. This action opens a save dialog, allowing us to choose the destination and file format for our QR code image.

How to Create a QR Code Generator Application In C#: Figure 26 - Save Dialog

Once saved, a success message confirms that the QR code has been stored successfully.

How to Create a QR Code Generator Application In C#: Figure 27 - Success Message

If we need to start over or create a new QR code, clicking the "Reset Form" button reverts the form to its original state, clearing all fields and selections, ready for the next QR code generation.

How to Create a QR Code Generator Application In C#: Figure 28 - Reset Form

Here is the saved QR code generated by IronQR:

How to Create a QR Code Generator Application In C#: Figure 29 - QR Code Output

Conclusion

In conclusion, this guide has walked you through the process of generating QR codes using the IronQR library in a C# application. By breaking down the steps from setting up your project in Visual Studio, integrating the IronQR library, designing a user-friendly interface, and writing the backend logic, we've demonstrated how accessible it is to add QR code functionality to your applications.

For those interested in exploring the capabilities of IronQR further, it's worth noting that IronQR offers a free trial to get you started. Should you decide to integrate IronQR into your projects, licenses start at $749, providing a cost-effective solution for professional-grade QR code generation.

< PREVIOUS
How to read QR Codes in C#
NEXT >
How to Generate QR code using QRCoder compare to IronQR in .NET 6

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 20,066 View Licenses >