Our Customers
Contact Us Email: support@barcodelib.com
Home > .NET Barcode > How to barcode in C#? > How to generate barcode using C# in ASP.NET Core web app?
Download Barcode for .NET Suite Trial

How to create barcodes in C# WPF Windows application

Detailed guide for generating and printing Barcodes in Windows Presentation Foundation (WPF) app Using C# Code
How to create barcode using C# in ASP.NET Core web app?

Requirements

This is a simple WPF tutorial that teaches the basics of building a WPF (.NET Core) application to customize, preview, generate QR Code barcode images on the WPF Windows Form.

After finish the tutorial, you can also further customize the C# to add more barcode options, such as generating styled QR Code with logo image inside.

1. Create a new WPF (.NET Core) app

Here we will quickly create a new ASP.NET Core web app using Visual Studio .NET
  • Start Visual Studio and select Create a new project
  • In the Create a new project dialog, select WPF Application, and select button Next.
  • In the Configure your new project dialog, enter BarcodeLib.Create.WPFCoreDemo for Project name. It is important to name the proejct BarcodeLib.Create.WPFCoreDemo, including letter case, so the namespaces will match when you copy, paste the following C# example source code.
  • Select button Create
  • In the Additional information diaplog, select .NET 6.0 or .NET 7.0 for the Framework dropdowns. Select button Create.
  • Now we have created a new WPF application project successfully.

2. Install Barcode Generator library and Nuget package

Now we will add and install BarcodeLib C# barcode generator library (dll file) to the new WPF application project and also add the a Nuget package named "System.Drawing.Common".

Add BarcodeLib C# Barcode Generator library

  • In the Solution Explorer window, right click Dependencies, select Add Project Reference...
  • Select button Browse... in the Reference Manager dialog.
  • Choose dll file BarcodeLib.Barcode.Common.dll from BarcodeLib downloaded package /Dll/net-standard/
  • Check BarcodeLib.Barcode.Common.dll is selected, and select button OK


  • Now we have added the barcodelib barcode generator library dll to the WPF project. We will start to add a library "System.Drawing.Common" from Nuget


  • Install NuGet Package

  • Right click Dependencies, select Manage NuGet Packages...
  • Navigate to tab Browse in the NuGet Package Manager
  • Enter System.Drawing.Common to search NuGet package
  • Choose the first searched result System.Drawing.Common by Microsoft
  • Select button Install


  • Now we have added the C# barcode generator library dll file and nuget package to the WPF project successfully.



3. Apply function codes in the user interface in WPF Designer

  • Select and click MainWindow.xaml in the "Solution Explorer" to open the WPF Designer.
  • Switch to XAML view
  • Add two GroupBox elements inside the Grid tag
    <Window x:Class="BarcodeLib.Create.WPFCoreDemo.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:BarcodeLib.Create.WPFCoreDemo"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="480" />
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>
            <GroupBox Header="Preview" Background="LightGray">
            </GroupBox>
            <GroupBox Header="QR Code Settings" Grid.Column="1">
            </GroupBox>
        </Grid>
    </Window>
    


    Now you will find two group boxes added on the MainWindow


  • Copy the following xml code to add an Image control to preview the QR Code on the WPF app main Window.

    <GroupBox Header="Preview" Background="LightGray">
        <Border BorderThickness="2" BorderBrush="Blue" Width="404" Height="404">
            <Image Name="imgReview" Width="400" Height="400" />
        </Border>
    </GroupBox>
    

  • Add barcode setting option controls to customze the generated QR Code.

            <GroupBox Header="QR Code Settings" Grid.Column="1">
                <Canvas>
                    <!-- Data to encode -->
                    <Label Content="Data:" Canvas.Left="10" Canvas.Top="5" />
                    <TextBox Name="tbData" Canvas.Left="110" Canvas.Top="10" Width="160" Height="90"
                    TextWrapping="Wrap"/>
                    <!-- Barcode Width -->
                    <Label Content="Barcode Width:" Canvas.Left="10" Canvas.Top="105" />
                    <TextBox Name="tbBarcodeWidth" Canvas.Left="160" Canvas.Top="110" Width="60" />
                    <Label Content="inches" Canvas.Left="225" Canvas.Top="105" />
                    <!-- Resolution -->
                    <Label Content="Resolution:" Canvas.Left="10" Canvas.Top="135" />
                    <TextBox Name="tbResolution" Canvas.Left="160" Canvas.Top="140" Width="60" />
                    <Label Content="dots per inch" Canvas.Left="225" Canvas.Top="135" />
                    <!-- Fore Color -->
                    <Label Content="Fore Color:" Canvas.Left="10" Canvas.Top="165" />
                    <TextBox Name="tbForeColor" Canvas.Left="160" Canvas.Top="170" Width="60" />
                    <Rectangle Name="rectForeColor" Canvas.Left="230" Canvas.Top="172"
                    Width="15" Height="15" Stroke="Black" />
                    <!-- Back Color -->
                    <Label Content="Back Color:" Canvas.Left="10" Canvas.Top="195" />
                    <TextBox Name="tbBackColor" Canvas.Left="160" Canvas.Top="200" Width="60" />
                    <Rectangle Name="rectBackColor" Canvas.Left="230" Canvas.Top="202"
                    Width="15" Height="15" Stroke="Black"/>
                    <!-- Preview -->
                    <Button Name="btReview" Content="Review" Canvas.Left="60" Canvas.Bottom="20"
                Width="80" />
                    <!-- Save -->
                    <Button Name="btSave" Content="Save" Canvas.Left="180" Canvas.Bottom="20"
                Width="80" />
                </Canvas>
            </GroupBox>
    


    Now we can find the preview image control on the left and other barcode options controls on the right of the main window.

  • The xml code below is the complete code for MainWindow.xaml with controls events added.

    Copy the following C# source code to set the barcode option controls default values.

    <Window x:Class="BarcodeLib.Create.WPFCoreDemo.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:BarcodeLib.Create.WPFCoreDemo"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="480" />
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>
            <GroupBox Header="Preview" Background="LightGray">
            </GroupBox>
            <GroupBox Header="QR Code Settings" Grid.Column="1">
            </GroupBox>
    
            <GroupBox Header="Preview" Background="LightGray">
                <Border BorderThickness="2" BorderBrush="Blue" Width="404" Height="404">
                    <Image Name="imgReview" Width="400" Height="400" />
                </Border>
            </GroupBox>
    
            <GroupBox Header="QR Code Settings" Grid.Column="1">
                <Canvas>
                    <!-- Data to encode -->
                    <Label Content="Data:" Canvas.Left="10" Canvas.Top="5" />
                    <TextBox Name="tbData" Canvas.Left="110" Canvas.Top="10" Width="160" Height="90"
                    TextWrapping="Wrap"/>
                    <!-- Barcode Width -->
                    <Label Content="Barcode Width:" Canvas.Left="10" Canvas.Top="105" />
                    <TextBox Name="tbBarcodeWidth" Canvas.Left="150" Canvas.Top="110" Width="60"
                            TextChanged="tbBarcodeWidth_TextChanged"
                            PreviewTextInput="tbBarcodeWidth_PreviewTextInput" />
                    <Label Content="inches" Canvas.Left="215" Canvas.Top="105" />
                    <!-- Resolution -->
                    <Label Content="Resolution:" Canvas.Left="10" Canvas.Top="135" />
                    <TextBox Name="tbResolution" Canvas.Left="150" Canvas.Top="140" Width="60"
                            TextChanged="tbResolution_TextChanged"
                            PreviewTextInput="tbResolution_PreviewTextInput" />
                    <Label Content="dots per inch" Canvas.Left="215" Canvas.Top="135" />
                    <!-- Fore Color -->
                    <Label Content="Fore Color:" Canvas.Left="10" Canvas.Top="165" />
                    <TextBox Name="tbForeColor" Canvas.Left="150" Canvas.Top="170" Width="60"
                            TextChanged="tbForeColor_TextChanged"                         
                            PreviewTextInput="tbColor_PreviewTextInput" />
                    <Rectangle Name="rectForeColor" Canvas.Left="220" Canvas.Top="172"
                    Width="15" Height="15" Stroke="Black" />
                    <!-- Back Color -->
                    <Label Content="Back Color:" Canvas.Left="10" Canvas.Top="195" />
                    <TextBox Name="tbBackColor" Canvas.Left="150" Canvas.Top="200" Width="60"
                            TextChanged="tbBackColor_TextChanged"
                            PreviewTextInput="tbColor_PreviewTextInput" />
    
    
                    <Rectangle Name="rectBackColor" Canvas.Left="220" Canvas.Top="202"
                    Width="15" Height="15" Stroke="Black"/>
                    <!-- Preview -->
                    <Button Name="btReview" Content="Review" Canvas.Left="60" Canvas.Bottom="20"
                            Width="80" Click="btReview_Click" />
                    <!-- Save -->
                    <Button Name="btSave" Content="Save" Canvas.Left="180" Canvas.Bottom="20"
                            Width="80" Click="btSave_Click" />
                </Canvas>
            </GroupBox>
        </Grid>
    </Window>
    


4. Add C# codes to controls event handler

Here is the complete C# code for MainWindow.xaml.cs with evets implemented.

using BarcodeLib.Barcode;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BarcodeLib.Create.WPFCoreDemo
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public const int Preview_Width = 400;

        public MainWindow()
        {
            InitializeComponent();

            //  Initial TextBox
            this.tbData.Text = "QR Code";
            this.tbBarcodeWidth.Text = "2";     //  2 inches
            this.tbResolution.Text = "300";     //  300 dots per inch
            this.tbForeColor.Text = "000000";   //  Black
            this.tbBackColor.Text = "FFFFFF";   //  White

            //  Show preview barcode image.
            updatePreviewImage();
        }

        private void tbBarcodeWidth_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {   //  Barcode Width must be a float value
            e.Handled = !isValidChars(e.Text, "0123456789.");
        }
        private void tbResolution_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {   //  Resolution must be an int value
            e.Handled = !isValidChars(e.Text, "0123456789");
        }
        private void tbColor_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {   //  Fore Color and Back Color must be a Hex char string
            e.Handled = !isValidChars(e.Text, "0123456789ABCDEFabcdef");
        }
        private bool isValidChars(String content, String validCharSet)
        {
            foreach (char c in content)
            {
                if (!validCharSet.Contains(c))
                    return false;
            }
            return true;
        }

        private void tbBarcodeWidth_TextChanged(object sender, TextChangedEventArgs e)
        {
            float result;
            bool isValid = float.TryParse(tbBarcodeWidth.Text, out result);
            if (isValid) isValid = result > 0;
            updateTextBoxBackground(this.tbBarcodeWidth, isValid);
        }
        private void tbResolution_TextChanged(object sender, TextChangedEventArgs e)
        {
            int result;
            bool isValid = int.TryParse(tbBarcodeWidth.Text, out result);
            if (isValid) isValid = result > 0;
            updateTextBoxBackground(this.tbBarcodeWidth, isValid);
        }
        //  Set background color of the TextBox to Red if the Text is invalid.
        private void updateTextBoxBackground(TextBox tb, bool isValid)
        {
            System.Windows.Media.Color normal = System.Windows.Media.Color.FromRgb(255, 255, 255);
            System.Windows.Media.Color error = System.Windows.Media.Color.FromRgb(255, 0, 0);
            tb.Background = new SolidColorBrush(isValid ? normal : error);
        }

        private void tbForeColor_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.rectForeColor == null)
                return;

            try
            {
                System.Drawing.Color color = parseColorString(this.tbForeColor.Text);
                //  Not transparent
                if (color != System.Drawing.Color.Transparent)
                {
                    System.Windows.Media.Color mColor = System.Windows.Media.Color.FromRgb(color.R, color.G, color.B);
                    this.rectForeColor.Fill = new System.Windows.Media.SolidColorBrush(mColor);
                    this.rectForeColor.Visibility = Visibility.Visible;
                }
                //  Hidden Rectangle if set to transparent.
                else
                    this.rectForeColor.Visibility = Visibility.Hidden;
            }
            catch (Exception)
            {
                this.rectForeColor.Visibility = Visibility.Hidden;
            }

            int len = this.tbForeColor.Text.Length;
            bool isValid = len == 6;
            updateTextBoxBackground(this.tbForeColor, isValid);
        }
        private void tbBackColor_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.rectBackColor == null)
                return;

            try
            {
                System.Drawing.Color color = parseColorString(this.tbBackColor.Text);
                //  Not transparent
                if (color != System.Drawing.Color.Transparent)
                {
                    System.Windows.Media.Color mColor = System.Windows.Media.Color.FromRgb(color.R, color.G, color.B);
                    this.rectBackColor.Fill = new System.Windows.Media.SolidColorBrush(mColor);
                    this.rectBackColor.Visibility = Visibility.Visible;
                }
                //  Hidden Rectangle if set to transparent.
                else
                    this.rectBackColor.Visibility = Visibility.Hidden;
            }
            catch (Exception)
            {
                this.rectBackColor.Visibility = Visibility.Hidden;
            }

            int len = this.tbBackColor.Text.Length;
            bool isValid = len == 0 || len == 6;
            updateTextBoxBackground(this.tbBackColor, isValid);
        }
        //  Parse Color string to System.Drawing.Color
        private System.Drawing.Color parseColorString(String rrggbb)
        {
            //  Input must be a string with 6 hex chars.
            if (rrggbb == null || rrggbb.Length != 6)
                return System.Drawing.Color.Transparent;

            try
            {
                int r = hexCharToInt(rrggbb[0]) * 16 + hexCharToInt(rrggbb[1]);
                int g = hexCharToInt(rrggbb[2]) * 16 + hexCharToInt(rrggbb[3]);
                int b = hexCharToInt(rrggbb[4]) * 16 + hexCharToInt(rrggbb[5]);
                return System.Drawing.Color.FromArgb(r, g, b);
            }
            catch (Exception)
            {
                return System.Drawing.Color.Transparent;
            }
        }
        //  Convert Hex Char to integer.
        //  Valid Input: '0' ~ '9', 'A' ~ 'F' or 'a' ~ 'f'.
        //  Throw exception if input is invalid.
        private int hexCharToInt(char c)
        {
            if (c >= '0' && c <= '9')
                return (int)c - (int)'0';
            if (c >= 'A' && c <= 'F')
                return (int)c - (int)'A' + 10;
            if (c >= 'a' && c <= 'f')
                return (int)c - (int)'a' + 10;
            throw new Exception("Invalid Hex. Char");
        }

        private void btReview_Click(object sender, RoutedEventArgs e)
        {
            updatePreviewImage();
        }
        private void updatePreviewImage()
        {
            try
            {
                QRCode qrcode = generateBarcodeObject();
                
                Bitmap bitmap = qrcode.drawBarcode();
                //  Resize barcode image to preview image.
                Bitmap previewImg = new Bitmap(Preview_Width, Preview_Width);
                using (Graphics g = Graphics.FromImage(previewImg))
                {
                    g.DrawImage(bitmap, 0, 0, previewImg.Width, previewImg.Height);
                }
                //  Update Image control
                using (MemoryStream ms = new MemoryStream())
                {
                    previewImg.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.StreamSource = ms;
                    bi.CacheOption = BitmapCacheOption.OnLoad;
                    bi.EndInit();
                    this.imgReview.Width = Preview_Width;
                    this.imgReview.Height = Preview_Width;
                    this.imgReview.Source = bi;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Create preview image failed. " + ex.Message);
            }
        }
        private QRCode generateBarcodeObject()
        {
            String data = this.tbData.Text;
            float imgWidthInInch;
            if (float.TryParse(this.tbBarcodeWidth.Text, out imgWidthInInch) == false)
                throw new Exception("Invalid Barcode Width");
            int dpi;
            if (int.TryParse(this.tbResolution.Text, out dpi) == false)
                throw new Exception("Invalid Resolution");
            if (this.tbForeColor.Text.Length != 6)
                throw new Exception("Invalid Fore Color");
            if (this.tbBackColor.Text.Length != 6
                && this.tbBackColor.Text.Length != 0)
                throw new Exception("Invalid Back Color");

            System.Drawing.Color foreColor = parseColorString(this.tbForeColor.Text);
            System.Drawing.Color backColor = parseColorString(this.tbBackColor.Text);
            QRCode barcode = new QRCode();
            barcode.Encoding = QRCodeEncoding.Auto;
            barcode.Version = QRCodeVersion.V1;
            barcode.ECL = QRCodeErrorCorrectionLevel.L;


            // Use Auto Size mode
            barcode.ResizeImage = true;
            // Set padding area to transparent
            barcode.ResizeImagePaddingTransparent = true;
            barcode.Data = data;
            barcode.UOM = UnitOfMeasure.INCH;
            barcode.Resolution = dpi;
            barcode.ImageWidth = imgWidthInInch;
            barcode.ImageHeight = imgWidthInInch;
            barcode.ModuleColor = foreColor;
            barcode.BackgroundColor = backColor;
            barcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Png;
            return barcode;
        }

        private void btSave_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "PNG Files (*.png)|*.png";
            saveFileDialog.DefaultExt = ".png";
            if (saveFileDialog.ShowDialog() == true)
            {
                String outputFilePath = saveFileDialog.FileName;
                try
                {
                    QRCode qrcode = generateBarcodeObject();
                    qrcode.drawBarcode(outputFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Save to file failed. " + ex.Message);
                }
            }
        }
    }
}


5. Run the demo web app

Now you have finished all C# coding in the WPF project. Run the WPF app directly from Visual Studio .NET.

You can preview the customized QR Code and save the generated barcode image file.

Related Barcode Library Tutorials
Barcode for Visual C#.NET - Other Supported Barcodes
Linear / 1D Barcodes:
Matrix / 2D Barcodes: