|
C# Barcode Generator for WPF
How to create barcodes using c# in WPF Windows application
Generate, create, print linear, 2d barcode image labels in c# WPF (.NET Core) windows applications.
In this short tutorial, you'll learn how to create linear, 2d barcodes in a new Windows Presentation Foundation (WPF) app with Visual Studio.
Once the WPF app has been generated, you can encode and generate QR Code barcodes on the WPF Windows, customize the QR Code
barcode settings on the Windows, and save the high resolution QR Code images on your computer local system.
After the tutorial, you can preview generated QR Code on the WPF main Window, with barcode image width, resolution, colors settings applied.
KeepAutomation C#.NET Barcode Generator library is an easy to use barcode generator library and controller for .NET (.net core, framework) applications.
- Generate QR Code, Data Matrix, PDF417 2d barcodes in C# application, also create Code 39, Code 128, EAN-13, UPC-A 20+ linear barcodes in C# .NET projects
- Compatible with GS1 System, and support Unicode encoding in 2d barcodes
- Easy to enable barcode generation in your ASP.NET Core, framework, Razor pages, MVC web applications
- Support both System.Drawing.Common for Windows development and SkiaSharp for Linux, MacOS, non-Windows development
- Fully support .NET 8, 7, 6, 5, .NET Core 3.x, 2.x ASP.NET Core web apps and .NET Framework 4.x, 3,x, 2.x ASP.NET web applications
- Reliable C# barcode generator component to print high resolution dpi barcode for all scanners and printers
How to use C# to generate barcodes in WPF .NET Core Windows application?
Step 1: Create a new WPF Core Windows application project
1.1: Start Visual Studio 2022 and choose "Create a new project".
Choose WPF Application in the dialog, and then press Next button.
1.2: Create a new project with name KeepAutomation.BarcodeGenerator.WPF.NET.Demo.
1.3: Select .NET 6.0 (Long-term support), and then press Create.
1.4: Now, all Visual Studio .NET auto-generated files could be found in the solution explorer.
Step 2: Add C# barcode generator library and NuGut package to the WPF project
2.1: Add required DLL reference KeepAutomation.Barcode.Standard.dll from downloaded package folder /DLL/NetStandard/
2.2: Right-click Dependencies in the Solution Explorer, and select Manage NuGet Packages.
Select Browse and use the search control to find System.Drawing.Common from the package source nugget.org.
Choose the version 6.0.0 or later to install the package.
Check Packages in the Solution Explorer to ensure the installation is success.
Step 3: Design the user interface in WPF Designer
Select MainWindow.xaml in the Solution Explorer to open the WPF Designer.
3.1: adjust attributes of the Window tag as below
<Window x:Class="KeepAutomation.BarcodeGenerator.WPF.NET.Demo.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:KeepAutomation.BarcodeGenerator.WPF.NET.Demo"
mc:Ignorable="d"
Title="MainWindow" Height="480" Width="800" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Grid>
</Grid>
</Window>
3.2: add two GroupBox controls (with header Preview and QRCode Settings) into the <Grid> tag.
<Window x:Class="KeepAutomation.BarcodeGenerator.WPF.NET.Demo.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:KeepAutomation.BarcodeGenerator.WPF.NET.Demo"
mc:Ignorable="d"
Title="MainWindow" Height="480" 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="QRCode Settings" Grid.Column="1">
</GroupBox>
</Grid>
</Window>
Design view
3.3: add an Image control (with name imgReview) to GroupBox Preview for showing preview barcode image;
and with a Border that its border thickness is 2 and color is blue.
<GroupBox Header="Preview" Background="LightGray">
<Border BorderThickness="2" BorderBrush="Blue" Width="404" Height="404">
<Image Name="imgReview" Width="400" Height="400" />
</Border>
</GroupBox>
Design view
3.4: add a Canvas with all required Controls to the GroupBox QRCode Settings.
<GroupBox Header="QRCode Settings" Grid.Column="1">
<Canvas>
<!-- Data Message -->
<Label Content="Data Message:" 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="dpi" 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>
- Data Message: TextBox name: tbData
- Barcode Width: TextBox name: tbBarcodeWidth
- Resolution: TextBox name: tbResolution
- Fore Color: TextBox name: tbForeColor; Rectangle: rectForeColor
- Back Color: TextBox name: tbBackColor; Rectangle: rectBackColor
- Preview: Button name: btPreview
- Save: Button name: btSave
Design View
3.5: initial TextBox controls in the code-behind C# file.
Select MainWindow.xaml.cs in the Solution Explorer to open the code-behind file.
Add initial codes to the constructor as below.
public partial class MainWindow : Window
{
public const int Preview_Width = 400;
public MainWindow()
{
InitializeComponent();
// Initial TextBox
this.tbData.Text = "QRCode";
this.tbBarcodeWidth.Text = "2"; // 2 inches
this.tbResolution.Text = "120"; // 120 pixels per inch
this.tbForeColor.Text = "000000"; // Black
this.tbBackColor.Text = "FFFFFF"; // White
// Show preview barcode image.
updatePreviewImage();
}
Note: Preview_width MUST BE equal to the width and height of the Image control.
Step 4: Add event handler to controls
4.1: add TextChanged and PreviewTextInput event handler for four TextBox controls.
TextBox: tbBarcodeWidth
<TextBox Name="tbBarcodeWidth" Canvas.Left="160" Canvas.Top="110" Width="60"
TextChanged="tbBarcodeWidth_TextChanged"
PreviewTextInput="tbBarcodeWidth_PreviewTextInput" />
TextBox: tbResolution
<TextBox Name="tbResolution" Canvas.Left="160" Canvas.Top="140" Width="60"
TextChanged="tbResolution_TextChanged"
PreviewTextInput="tbResolution_PreviewTextInput" />
TextBox: tbForeColor
<TextBox Name="tbForeColor" Canvas.Left="160" Canvas.Top="170" Width="60"
TextChanged="tbForeColor_TextChanged"
PreviewTextInput="tbColor_PreviewTextInput" />
TextBox: tbBackColor
<TextBox Name="tbBackColor" Canvas.Left="160" Canvas.Top="200" Width="60"
TextChanged="tbBackColor_TextChanged"
PreviewTextInput="tbColor_PreviewTextInput" />
Then, add seven empty event handler methods (as below) to the code-behind C# file MainWindow.xaml.cs.
The implementation of these methods would be added in the next section.
private void tbBarcodeWidth_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
}
private void tbResolution_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
}
private void tbColor_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
}
private void tbBarcodeWidth_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void tbResolution_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void tbForeColor_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void tbBackColor_TextChanged(object sender, TextChangedEventArgs e)
{
}
4.2: add Click event handler to those two Button controls.
Button: btReview
<Button Name="btReview" Content="Review" Canvas.Left="60" Canvas.Bottom="20"
Width="80" Click="btReview_Click" />
Button: btSave
<Button Name="btSave" Content="Save" Canvas.Left="180" Canvas.Bottom="20"
Width="80" Click="btSave_Click" />
Then, add two empty event handler methods (as below) to the code-behind C# file
MainWindow.xaml.cs. The implementation of these methods would be added in the next section.
private void btReview_Click(object sender, RoutedEventArgs e)
{
}
private void btSave_Click(object sender, RoutedEventArgs e)
{
}
Step 5: All C# source codes to implements events
For Events: tbBarcodeWidth_PreviewTextInput, tbResolution_PreviewTextInput, tbColor_PreviewTextInput
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;
}
For Events: tbBarcodeWidth_TextChanged, tbResolution_TextChanged
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);
}
For Events: tbForeColor_TextChanged, tbBackColor_TextChanged
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");
}
For Events: btReview_Click
private void btReview_Click(object sender, RoutedEventArgs e)
{
updatePreviewImage();
}
private void updatePreviewImage()
{
try
{
BarCode qrcode = generateBarcodeObject();
Bitmap bitmap = qrcode.generateBarcodeToBitmap();
// 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 BarCode 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);
BarCode barcode = new BarCode();
barcode.Symbology = Symbology.QRCode;
barcode.QRCodeDataMode = QRCodeDataMode.Auto;
barcode.QRCodeVersion = QRCodeVersion.V1;
barcode.QRCodeECL = QRCodeECL.L;
// Use Auto Size mode
barcode.AutoSizeAdjust = true;
// Set padding area to transparent
barcode.AutoSizePaddingTransparent = true;
barcode.CodeToEncode = data;
barcode.BarcodeUnit = BarcodeUnit.Inch;
barcode.DPI = dpi;
barcode.BarCodeWidth = imgWidthInInch;
barcode.BarCodeHeight = imgWidthInInch;
barcode.ForeColor = foreColor;
barcode.BackColor = backColor;
barcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Png;
return barcode;
}
For Events: btSave_Click
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
{
BarCode qrcode = generateBarcodeObject();
qrcode.generateBarcodeToImageFile(outputFilePath);
}
catch (Exception ex)
{
MessageBox.Show("Save to file failed. " + ex.Message);
}
}
}
Step 6: Run WPF app from Visual Studio
Now the whole WPF project C# source codes are done. The app is ready to run. You can run the WPF app from Visual Studio directly.
|