IronQR Tutoriales Generador QR en C# C# Aplicación generadora de códigos QR Curtis Chau Actualizado:10 de enero de 2026 Descargar IronQR Descarga de NuGet Prueba gratis Copia para LLM Copia para LLM Copiar página como Markdown para LLM Abrir en ChatGPT Pregunta a ChatGPT sobre esta página Abrir en Gemini Pregunte a Gemini sobre esta página Abrir en Grok Pregunte a Grok sobre esta página Abierto en perplejidad Pregunta a Perplexity sobre esta página Compartir Compartir en Facebook Compartir en X (Twitter) Compartir en LinkedIn Copiar URL Enviar artículo This article was translated from English: Does it need improvement? Translated View the article in English IronQR es la nueva biblioteca de códigos QR .NET de Iron Software. Aprovecha las técnicas de aprendizaje automático más avanzadas para leer códigos QR desde cualquier ángulo con una precisión del 99,99 %. ¡Genera y personaliza nuevos códigos QR fácilmente! ¡Empieza a usar IronQR ahora! ¡Bienvenido a nuestra guía sobre la creación de códigos QR utilizando C#! Los códigos QR y el .NET barcode DLL se han convertido en formas populares para compartir información de manera rápida y eficiente. Ya sea que esté desarrollando una aplicación, administrando un sitio web, o buscando una manera ingeniosa de compartir enlaces, estos códigos pueden ser increíblemente útiles. En esta guía, demostraremos cómo generar códigos QR de manera eficiente usando IronQR, asegurando que pueda generar códigos QR adaptados a sus necesidades. Esta biblioteca facilita a cualquier persona que trabaje con C# crear códigos QR sin entrar en una lógica compleja. Le guiaremos por los pasos, asegurándonos de que tenga todo lo que necesita para comenzar. Ya sea que esté buscando añadir la funcionalidad de generador de códigos QR a su aplicación o simplemente curioso sobre cómo se hace, está en el lugar correcto. Empecemos. ## Cómo crear un generador de códigos QR en C# Crear una aplicación de Windows Forms en Visual Studio Instalar la biblioteca QR mediante NuGet Diseñar los elementos de frontend del formulario Escribir la lógica de la generación de QR Ejecutar la aplicación y comenzar a crear códigos QR Instalar la biblioteca generadora de códigos QR en C Comience a usar IronQR en su proyecto hoy con una prueba gratuita. Primer Paso: Comience gratis Antes de empezar, necesitamos instalar el paquete NuGet de IronQR. Install-Package IronQR IronQR: Biblioteca QR de C IronQR es una biblioteca de códigos QR en C# para integrar la funcionalidad de códigos QR en aplicaciones .NET. IronQR es compatible con una amplia gama de versiones de .NET y tipos de proyectos, incluidos C#, VB.NET, F#, .NET Core, .NET Standard, .NET Framework y más, asegurando compatibilidad con diversos entornos de desarrollo como Windows, Linux, macOS, iOS y Android. IronQR se distingue por sus características avanzadas, incluyendo la capacidad de leer códigos QR y generar códigos QR, soporte para múltiples formatos de imagen, y opciones de personalización como redimensionar, estilizar y agregar logos a los códigos QR. Algunas características clave de IronQR IronQR extiende su funcionalidad más allá de la generación básica de códigos QR, ofreciendo varias características diseñadas para acomodar una amplia gama de tareas relacionadas con códigos QR. Vamos a repasar estas características y verificar sus códigos de ejemplo que podrá integrar en cualquier tipo de plantilla de aplicación .NET, como una aplicación de consola. Leer códigos QR IronQR se destaca en decodificación de códigos QR, proporcionando a los usuarios una manera sencilla de acceder a la información incrustada en los códigos QR. Puede extraer datos rápida y precisamente de los códigos QR, desde URLs simples hasta información incrustada compleja. :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 El proceso comienza incorporando los espacios de nombres necesarios: IronQr e Iron Software.Drawing, con una mención específica de Color del espacio de nombres Iron Software.Drawing para manejar manipulaciones de imágenes. Antes de sumergirse en el proceso de lectura de códigos QR, es esencial activar el software con su clave de licencia asignándola a IronQr.License.LicenseKey. El código luego procede a cargar la imagen del código QR desde un archivo usando AnyBitmap.FromFile("QRCode.png"). Con la imagen cargada, el siguiente paso involucra prepararla para la detección de códigos QR. Esta preparación se realiza creando un objeto QrImageInput, que sirve como contenedor para la imagen. El núcleo de esta característica radica en la clase QrReader, que se instancia y utiliza para realizar la operación de lectura de códigos QR. El lector analiza la imagen preparada, buscando cualquier código QR que contenga. El resultado de esta operación es una colección de objetos QrResult, cada uno representando un código QR detectado dentro de la imagen. Para acceder y utilizar los datos codificados en los códigos QR, el código itera sobre la colección de resultados usando un bucle foreach. Cada objeto QrResult contiene propiedades como el valor del código QR, al que se puede acceder y mostrar. Opciones de modo de lectura de QR personalizado IronQR proporciona diferentes modos para leer códigos QR, lo que lo hace versátil para diversas necesidades. Modo de Escaneo Mixto: Equilibra velocidad y precisión, útil para códigos QR que no están claros o parcialmente ocultos. Modo de Escaneo de Aprendizaje Automático (ML): Utiliza tecnología avanzada para leer códigos QR dañados o difíciles de leer, ideal para escenarios difíciles de detectar. Modo de Escaneo Básico: La forma más sencilla y rápida, para códigos QR claros y directos. :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 Leer códigos QR avanzados Las capacidades avanzadas de lectura de códigos QR de IronQR proporcionan un enfoque integral para escanear y decodificar códigos QR. Este conjunto de funciones va más allá de la lectura básica, ofreciendo un nivel más profundo de interacción y extracción de datos. :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 Para crear un generador de códigos QR utilizando la biblioteca IronQR en una aplicación C#, siga estos pasos con cuidado. Esta guía lo llevará a través de la configuración de una aplicación en formulario de Windows, la instalación de la biblioteca IronQR, la escritura del código para generar un código QR y la comprensión del resultado. Paso 1: Crear una aplicación de Windows en Visual Studio Comience lanzando Visual Studio en su computadora. Haga clic en el botón "Crear un nuevo proyecto". Seleccione Aplicación de Windows Forms como tipo de proyecto. Asegúrese de elegir C# como el idioma. Ingrese un nombre para su proyecto y seleccione la ubicación. Haga clic derecho en su proyecto en el Explorador de soluciones y seleccione Administrar paquetes NuGet. Luego, en la siguiente pantalla, seleccione .NET framework. Luego haga clic en Crear. Escriba IronQR en el cuadro de búsqueda y presione Enter. Paso 2: Instalar la biblioteca IronQR Ahora es el momento de instalar la biblioteca IronQR en el proyecto. Puede instalar la biblioteca IronQR a través de diferentes métodos. Instalar mediante el Administrador de paquetes NuGet Encuentre IronQR en la lista y haga clic en Instalar. Vaya a Herramientas > Administrador de paquetes NuGet > Consola del administrador de paquetes.  2. Escriba `Install-Package IronQR` y presione Enter. Encuentra IronQR en la lista y haz clic en Instalar. Instalar mediante la consola del administrador de paquetes NuGet Ve a Herramientas > Administrador de Paquetes NuGet > Consola del Administrador de Paquetes. Escriba Install-Package IronQR y presione Enter. Paso 3: Diseño del frontend 3.1 Encabezado del título Al iniciar la aplicación Generador de Códigos QR, los usuarios son presentados inmediatamente con un encabezado llamativo titulado "Generador de QR IronQR", establecido en una fuente audaz y autoritaria. 3.2 Sección de entrada Entrada de texto para código QR Los usuarios pueden ingresar los datos para codificar en su QR. Selección de logotipo El área "Seleccionar Logo" permite una capa extra de personalización. Permite a los usuarios especificar el tamaño general del código QR. Configuración de color Proporciona una vista previa en tiempo real del código QR generado. 3.3 Parámetros de estilo Configuración de dimensiones Activa el proceso de creación del código QR. Configuración de márgenes Permite especificar el espacio blanco alrededor del QR. 3.4 Vista previa de salida Abre un cuadro de diálogo para guardar el código QR. 3.5 Botones de acción Generar QR Limpia todas las entradas y selecciones anteriores. Guardar código QR Abre un diálogo para guardar el código QR. Restablecer formulario Borra todas las entradas y selecciones anteriores. Paso 4: Escribir la lógica del backend 4.1 Configuración e inicialización Incluye los espacios de nombres necesarios: IronQr y 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 Configuración de la clave de licencia Proporciona componentes de diálogo de color y funciones de utilidad. 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 Reemplace "YOUR_LICENSE_KEY" con su clave de licencia. 4.3 Gestión de directorios Permite al usuario seleccionar un logo. :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 Contiene lógica para generar códigos QR basado en las entradas de usuario. :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 Selección de color Proporciona componentes de diálogo de color y funciones utilitarias. :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 El método UpdateColor toma el color seleccionado y lo convierte al formato Iron Software.Drawing.Color usando el string hexadecimal, y actualiza el color de primer plano o de fondo del código QR según la selección. También actualiza la UI para reflejar la nueva elección de 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 Agregar logotipo Gestiona el guardado del código QR generado. :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 Generación de código QR Limpia las entradas del usuario y restablece el estado del formulario. :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 El objeto QrOptions define el nivel de corrección de errores, mejorando la resistencia del código QR a daños u ocultación. El método CreateStyleOptions genera un objeto QrStyleOptions, que incluye los ajustes personalizados del usuario como colores, dimensiones y el logo. Así es el método en detalle: :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 Guardar el código QR Maneja el guardado del código QR generado. :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 Restablecer la aplicación Borra entradas del usuario y restablece el estado del formulario. :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 Manejo de errores Sigue la interfaz para ingresar datos, personalizar y guardar el código QR. :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 Ejemplo de código completo El código completo que combina todas las características anteriores se puede encontrar en el archivo de ejemplo vinculado a su proyecto. :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 Paso 5: Ejecutar la aplicación Cuando se ejecuta la aplicación, la ventana principal aparece organizada con secciones para entrada, estilo, salida y acciones. Siga la interfaz de usuario para ingresar datos, personalizar su código QR y generar y guardar el código QR como desee. Conclusión En conclusión, esta guía lo ha llevado a través del proceso de generación de códigos QR usando la biblioteca IronQR en una aplicación C#. Al desglosar los pasos desde configurar su proyecto en Visual Studio, integrar la biblioteca IronQR, diseñar una interfaz fácil de usar, y escribir la lógica backend, hemos demostrado cuán accesible es añadir funcionalidad de códigos QR a sus aplicaciones. Para aquellos interesados en explorar más a fondo las capacidades de IronQR, vale la pena señalar que IronQR ofrece una prueba gratuita para comenzar. Si decides integrar IronQR en tus proyectos, las licencias comienzan en $799, proporcionando una solución rentable para la generación de códigos QR de nivel profesional. Preguntas Frecuentes ¿Cómo puedo crear una aplicación generadora de códigos QR en C#? Para crear una aplicación generadora de códigos QR en C#, puedes usar la biblioteca IronQR. Comienza configurando una aplicación de Windows Forms en Visual Studio, instala IronQR a través de NuGet y diseña el frontend de tu aplicación. Implementa la lógica de generación de códigos QR usando las características de IronQR, como la selección de color y la incorporación de logotipos. ¿Cuáles son los beneficios de usar una biblioteca de códigos QR .NET? Una biblioteca de códigos QR .NET como IronQR ofrece características avanzadas como alta precisión en la lectura de códigos QR, opciones de personalización para generar códigos QR y soporte para varios entornos .NET. También permite el redimensionamiento y el estilizado de los códigos QR. ¿Cómo manejo los errores al generar códigos QR en C#? En C#, puedes manejar los errores durante la generación de códigos QR implementando mecanismos de manejo de errores adecuados usando bloques try-catch. IronQR facilita una gestión suave de errores, asegurando que cualquier problema durante la creación de códigos QR se aborde eficientemente. ¿Puedo incorporar logotipos en los códigos QR usando una biblioteca de códigos QR? Sí, puedes incorporar logotipos en los códigos QR usando la biblioteca IronQR. Esta característica te permite mejorar la imagen de marca de tus códigos QR incorporando logotipos personalizados en el diseño. ¿Cómo guardo los códigos QR generados en una aplicación C#? Puedes guardar los códigos QR generados en una aplicación C# usando la funcionalidad de IronQR para especificar directorios de almacenamiento. Esto te permite gestionar y almacenar eficientemente los códigos QR generados dentro de tu aplicación. ¿Qué pasos son necesarios para configurar una clave de licencia para una biblioteca de códigos QR? Para configurar una clave de licencia para IronQR, necesitas incorporar el código de licencia en tu aplicación. Esto generalmente involucra agregar líneas de código específicas proporcionadas por IronQR para activar la biblioteca con tu licencia comprada. ¿Cómo puedo estilizar códigos QR con colores específicos en mi aplicación C#? IronQR te permite estilizar códigos QR con colores específicos utilizando sus características de personalización de color. Puedes seleccionar colores para el primer plano y el fondo del código QR usando los cuadros de selección de color integrados en tu aplicación. ¿Cuál es el proceso para instalar una biblioteca de códigos QR en Visual Studio? Para instalar una biblioteca de códigos QR como IronQR en Visual Studio, usa el NuGet Package Manager. Busca 'IronQR' y haz clic en 'Instalar' para añadirlo a tu proyecto. Alternativamente, usa el Package Manager Console con el comando 'Install-Package IronQR'. Curtis Chau Chatea con el equipo de ingeniería ahora Escritor Técnico Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...Leer más ¿Listo para empezar? Nuget Descargas 58,270 | Versión: 2026.2 recién lanzado Descarga Gratis de NuGet Descargas totales: 58,270 Ver Licencias
Producto completamente funcional Obtén 30 días de producto completamente funcional.Instálalo y ejecútalo en minutos.
Soporte técnico 24/5 Acceso completo a nuestro equipo de soporte técnico durante tu prueba del producto
Se responde a todas sus preguntas para asegurarse de que dispone de toda la información que necesita. (Sin ningún tipo de compromiso)