Saltar al pie de página
USO DE IRONBARCODE
Cómo Generar un Código QR Usando C# con IronBarcode

Cómo Generar Código QR en Aplicaciones Windows en C#

This tutorial provides an in-depth look at how to create QR codes, which are becoming increasingly popular in industrial applications and the retail sector. The IronBarcode library, one of the most popular and powerful libraries, will be used to demonstrate how to generate QR codes.

How to Generate QR Codes in C# Windows Forms Applications

  1. Create a Windows Forms Application in Microsoft Visual Studio
  2. Installing the QR code library
  3. Importing namespaces to create barcodes
  4. Creating a QR code with one line of code
  5. Adding a logo to a QR code image
  6. Saving an image as PDF or HTML

1. Create a Windows Forms Application in Microsoft Visual Studio

Open Visual Studio > Click on Create New Project > Select Windows Forms Application Template > Press Next > Name the Project > Press Next > Select your Target .NET Framework > Click the Create button.

After creating the project, design the form using the following controls from the Visual Studio toolbox: PictureBox, Label, TextBox, and Button.

How to Generate QR Code in C# Windows Applications, Figure 1: A Windows Forms Application UI to load an image and generate a QR Code A Windows Forms Application UI to load an image and generate a QR Code

2. Install the QR Code Generator .NET Library in C#

The first step is to install the barcode library. You can do this by using one of the following three methods:

2.1. Package Manager Console

Write the following command in the Package Manager Console. It will download and install the package for you.

Install-Package BarCode

How to Generate QR Code in C# Windows Applications, Figure 2: Installation progress in Package Manager Console UI Installation progress in Package Manager Console UI

2.2. NuGet Packages Manager Solution

You can also install the barcode library using the NuGet Package Solution. Simply follow these steps:

Click on Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

This will open the NuGet Package Manager for you. Click on Browse, search for BarCode, and then install the class library.

How to Generate QR Code in C# Windows Applications, Figure 3: Finding BarCode library in NuGet Package Manager Finding BarCode library in NuGet Package Manager

As an alternative, the IronBarCode.Dll can be downloaded and added to your project as a reference from .NET Barcode DLL.

3. Importing NameSpaces

For this tutorial, to ensure adequate references, the IronBarCode namespace along with other system assemblies is necessary.

using IronBarCode; // Provides functionality for QR and barcode generation
using System; // Contains fundamental classes and base classes that define commonly-used value and reference data types
using System.Drawing; // Provides access to GDI+ basic graphic functionality
using System.Linq; // Provides classes and interfaces that support queries
using IronBarCode; // Provides functionality for QR and barcode generation
using System; // Contains fundamental classes and base classes that define commonly-used value and reference data types
using System.Drawing; // Provides access to GDI+ basic graphic functionality
using System.Linq; // Provides classes and interfaces that support queries
Imports IronBarCode ' Provides functionality for QR and barcode generation
Imports System ' Contains fundamental classes and base classes that define commonly-used value and reference data types
Imports System.Drawing ' Provides access to GDI+ basic graphic functionality
Imports System.Linq ' Provides classes and interfaces that support queries
$vbLabelText   $csharpLabel

4. Create a QR Code with 1 Line of Code

The following sample code allows you to generate a QR code image with just one line of code. Enter the desired text into the text box for which you want to generate a QR code. Place this code in the "Generate PNG" button click event. The QR code images can be saved in PNG format.

// Simple QR Code generation
private void button1_Click(object sender, EventArgs e)
{
    // Generate a QR code from the text provided in the TextBox
    GeneratedBarcode qrCode = QRCodeWriter.CreateQrCode(textBox1.Text);

    // Save the generated QR code as a PNG file
    qrCode.SaveAsPng("QrCode.png");
}
// Simple QR Code generation
private void button1_Click(object sender, EventArgs e)
{
    // Generate a QR code from the text provided in the TextBox
    GeneratedBarcode qrCode = QRCodeWriter.CreateQrCode(textBox1.Text);

    // Save the generated QR code as a PNG file
    qrCode.SaveAsPng("QrCode.png");
}
' Simple QR Code generation
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
	' Generate a QR code from the text provided in the TextBox
	Dim qrCode As GeneratedBarcode = QRCodeWriter.CreateQrCode(textBox1.Text)

	' Save the generated QR code as a PNG file
	qrCode.SaveAsPng("QrCode.png")
End Sub
$vbLabelText   $csharpLabel

Here is the output of the QR code generator:

How to Generate QR Code in C# Windows Applications, Figure 4: QR code of: https://ironsoftware.com/csharp/barcode/docs/ QR code of: https://ironsoftware.com/csharp/barcode/docs/

5. Adding a Logo to a QR Code Image

By using the CreateQrCodeWithLogo method from the QRCodeWriter class, additional information, such as a logo, can be added to the QR code. The sample code illustrates how easy this is.

Browse the logo from your computer, and it will open in PictureBox. The code goes as follows:

// Open file dialog to select an image
OpenFileDialog open = new OpenFileDialog();
// Set image file filters to ensure valid image types are opened
open.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg; *.png; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK) {
    // Display image in PictureBox and store file path for later use
    pictureBox1.Image = new Bitmap(open.FileName);
    // Store image file path in class data member
    ImageFileName = open.FileName;
}
// Open file dialog to select an image
OpenFileDialog open = new OpenFileDialog();
// Set image file filters to ensure valid image types are opened
open.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg; *.png; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK) {
    // Display image in PictureBox and store file path for later use
    pictureBox1.Image = new Bitmap(open.FileName);
    // Store image file path in class data member
    ImageFileName = open.FileName;
}
' Open file dialog to select an image
Dim open As New OpenFileDialog()
' Set image file filters to ensure valid image types are opened
open.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg; *.png; *.jpeg; *.gif; *.bmp"
If open.ShowDialog() = DialogResult.OK Then
	' Display image in PictureBox and store file path for later use
	pictureBox1.Image = New Bitmap(open.FileName)
	' Store image file path in class data member
	ImageFileName = open.FileName
End If
$vbLabelText   $csharpLabel

Next, simply type the text in the text box, place this code in the Generate PNG button, and click.

// Generate a QR code with a logo
GeneratedBarcode qrCode = QRCodeWriter.CreateQrCodeWithLogo(textBox1.Text, ImageFileName, 500);
// Save the generated QR code with logo as a PNG file
qrCode.SaveAsPng("QrCodeWithImage.png");
// Generate a QR code with a logo
GeneratedBarcode qrCode = QRCodeWriter.CreateQrCodeWithLogo(textBox1.Text, ImageFileName, 500);
// Save the generated QR code with logo as a PNG file
qrCode.SaveAsPng("QrCodeWithImage.png");
' Generate a QR code with a logo
Dim qrCode As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo(textBox1.Text, ImageFileName, 500)
' Save the generated QR code with logo as a PNG file
qrCode.SaveAsPng("QrCodeWithImage.png")
$vbLabelText   $csharpLabel

This code adds the Iron logo to the barcode. It automatically sizes it to an appropriate size where the pure code is still readable and aligns that logo to the QR code square grid so that it looks appropriate.

How to Generate QR Code in C# Windows Applications, Figure 5: C# Create QR Code With Logo Image C# Create QR Code With Logo Image

6. Save as a PDF or HTML Image

Finally, the generated QR code can be saved as a PDF or HTML image. The final line of code opens the PDF in your default PDF browser for your convenience. Add the SaveAsPdf in the Generate PDF button and SaveAsHtmlFile in the Generate HTML button.

// Generate a QR code with a logo
GeneratedBarcode qrCode = QRCodeWriter.CreateQrCodeWithLogo(textBox1.Text, ImageFileName, 500);

// Save the QR code as a PDF file
qrCode.SaveAsPdf("QRWithLogo.pdf");

// Also, save the QR code as an HTML file
qrCode.SaveAsHtmlFile("QRWithLogo.html");
// Generate a QR code with a logo
GeneratedBarcode qrCode = QRCodeWriter.CreateQrCodeWithLogo(textBox1.Text, ImageFileName, 500);

// Save the QR code as a PDF file
qrCode.SaveAsPdf("QRWithLogo.pdf");

// Also, save the QR code as an HTML file
qrCode.SaveAsHtmlFile("QRWithLogo.html");
' Generate a QR code with a logo
Dim qrCode As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo(textBox1.Text, ImageFileName, 500)

' Save the QR code as a PDF file
qrCode.SaveAsPdf("QRWithLogo.pdf")

' Also, save the QR code as an HTML file
qrCode.SaveAsHtmlFile("QRWithLogo.html")
$vbLabelText   $csharpLabel

Summary

IronBarcode features a friendly API for developers to read and write data to barcodes and QR codes for C# .NET, optimizing accuracy and ensuring a low error rate in real-world cases. For more information about IronBarcode, please visit this documentation website.

Additionally, IronBarcode also supports reading barcodes from images, as well as providing extra options to read barcodes with more accuracy or apply filters to images.

Currently, if you buy the complete Iron Suite, you can get five libraries for the price of just two. Please visit the pricing page for more details.

Preguntas Frecuentes

¿Cómo puedo generar un código QR en aplicaciones de Windows C#?

Puedes usar la biblioteca IronBarcode para generar un código QR en aplicaciones de Windows C# utilizando el método QRCodeWriter.CreateQrCode. Esto te permite generar un código QR a partir de una entrada de texto y guardarlo como un archivo PNG.

¿Cuáles son los beneficios de usar IronBarcode para la generación de códigos QR?

IronBarcode proporciona una API fácil de usar para la generación de códigos QR con alta precisión y bajas tasas de error. También admite características adicionales como la adición de logos a los códigos QR y guardar códigos QR como archivos PDF o HTML.

¿Cómo configuro una aplicación de Windows Forms en Microsoft Visual Studio para la generación de códigos QR?

Para configurar una aplicación de Windows Forms en Microsoft Visual Studio, abre Visual Studio, selecciona 'Crear nuevo proyecto', elige 'Plantilla de aplicación de Windows Forms', nombra tu proyecto, selecciona el .NET Framework objetivo y haz clic en 'Crear'.

¿Cuál es el proceso de instalación de la biblioteca de códigos QR en un proyecto C#?

La biblioteca IronBarcode se puede instalar en un proyecto C# a través de la Consola del Administrador de Paquetes, la Solución del Gestor de Paquetes NuGet o descargando directamente el archivo IronBarCode.DLL.

¿Puedo agregar un logo a un código QR usando IronBarcode?

Sí, puedes agregar un logo a un código QR usando la biblioteca IronBarcode utilizando el método CreateQrCodeWithLogo de la clase QRCodeWriter, que te permite seleccionar una imagen de tu computadora.

¿Es posible convertir un código QR a PDF o HTML usando IronBarcode?

Sí, IronBarcode te permite convertir un código QR a un PDF usando SaveAsPdf o a un archivo HTML usando SaveAsHtmlFile.

¿Qué espacios de nombres son necesarios para generar códigos QR con IronBarcode?

Para generar códigos QR con IronBarcode, necesitas incluir el espacio de nombres 'IronBarCode', junto con espacios de nombres del sistema como System, System.Drawing y System.Linq.

¿Qué características adicionales de códigos de barras ofrece IronBarcode?

IronBarcode admite la lectura de varios formatos de códigos de barras a partir de imágenes, ofreciendo opciones para una mayor precisión y la capacidad de aplicar filtros para mejorar el reconocimiento de códigos de barras.

¿Dónde puedo encontrar documentación más detallada sobre el uso de IronBarcode?

Puedes visitar el sitio web de documentación de IronBarcode para obtener información más detallada y orientación sobre cómo usar la biblioteca para la generación de códigos QR y otras tareas relacionadas con códigos de barras.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más