How To: Write Your Very Own QR Code Generator in C#: Part 1

Write Your Very Own QR Code Generator in C#: Part 1


I will not go into some time-waster of a story about how I came to build this app. It was a prerequisite in a bigger project I am still tinkering with from time to time. 

What are QR Codes?

How to Write Your Very Own QR Code Generator in C#: Part 1

No doubt you have seen these  all over the place in recent years. Originally, QR (Quick Response) codes were used by car manufacturers to label different car parts, but recently, the smarty-pantses (yes, I am inventing words now) in marketing, have utilised these in adverts, coupons, presentations, flyers, on the backs of endangered pandas (just kidding), and many other things!

This effectively enabled users who own smartphones to access content more quickly than ever before. For example: Back in the day, when most of you young'uns were still way too young to even own a phone, if you saw an add in the paper which offered free pizza after 8 o'clock, you would have to tediously type the phone number in, by using your fingers (I know right? Such an inefficient method!), but with the help of modern technology, all I need to do now is to take my iPhone or Android, point it to a QR Code in the paper (by using an app obviously) and presto! It calls the phone number! Without me typing it in the old-fashioned way. OK, so maybe I overdid it with the sarcasm, but you get the idea, right?

So, if you are interested in more about the codes, hit up good ol' wiki and further your knowledge.

Now then, what was I saying? Oh yes, I will not go into long intros, (oops) hehe...

How to Write Your Very Own QR Code Generator in C#: Part 1

What I will discuss in this article, is how to build your own QR Code Generator.

The aim here is to get you into prodding at the way different types of data can be portrayed. While this tutorial will not explain what the code behind the ACTUAL qr matrix is, I hope it will get you interested in this sort of thing.

So, without further nonsense, let's review the requirements:

For this tutorial you will need:

  • Visual C# 2010
  • QR Toolkit found here (It's open source)
  • Basic - Intermediate C# knowledge

Let's begin:

Step 1 Adding References

  • Create a new windows forms project.
  • Download the QR Toolkit DLL and drop it into the bin\debug\ folder of your project.

To begin, switch back to Visual C# and click on ''Project'', located in the topmost toolbar and select "Add Reference.."

Then, click on the "Browse" tab and navigate to bin\debug\ and select the "MessagingToolkit.QRCode.dll";

Now it's time to populate our "using" clause. At the bottom of the "using" clause, add:

using MessagingToolkit.QRCode.Codec;

using MessagingToolkit.QRCode.Codec.Ecc;

using MessagingToolkit.QRCode.Codec.Data;

using MessagingToolkit.QRCode.Codec.Util;

Step 2 Coding the QR Generation Function

Just after the Form initialization clause, paste in the code below:

private Image QRGen(string input, int qrlevel)


            string toenc = input;

            MessagingToolkit.QRCode.Codec.QRCodeEncoder qe = new MessagingToolkit.QRCode.Codec.QRCodeEncoder();

            qe.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;

            qe.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L; // - Using LOW for more storage

            qe.QRCodeVersion = qrlevel;

            System.Drawing.Bitmap bm = qe.Encode(toenc);

            return bm;


Code Autopsy:

Line 1 - Declaration of our function. private Image (will return an image after processing), (string input,int qrlevel) - required input, a text that it will encode and the level of encoding.

Line 2 - Creation of a new instance of the QR encoder.

Line 3 - Setting the encode mode to byte.

Line 4 - Setting Error Correction.

Line 5 - Setting version to reflect level entered.

Line 6 - Setting the encoded picture to be placed in a new bitmap instance.

Line 7 - Return the bitmap instance.

Two things you need to REALLY pay attention to:

One: Error correction—Simply put, the higher the error correction level, the lower storage capacity you get. Using a high correction level, you will be able to embed a logo in the middle of the code (with a caveat) and still get a correct read!

Two: QRLevel—This governs how many alphanumeric characters you can enter in a code. The more characters, the bigger the output image. The levels are from 1-40, ranging from 17 to 7,089 alphanumeric characters in length (subject to correction level). Now that this is done, let's head to step 3.

Step 3 Layout

OK, this will differ due to everyone's own style of doing things. Effectively, the function I gave you above will do 99% of what the app should do. The other 1% is the additional controls I have put in place for my own spin of the app. So if you are content and confident with leaving us here and going to test it out, please do. Otherwise, read on.

Here is my current LAYOUT;

Components to note (for code purposes):

How to Write Your Very Own QR Code Generator in C#: Part 1

Step 4 The Rest of the App

OK and now the rest of my code (explanations in // comments):

private void button3_Click(object sender, EventArgs e)


            qr_pic.Image = QRGen(qrtext.Text, Convert.ToInt32(qrlev.Text));


//will generate the qr code, based on the contents of qrtext and qrlev text (converted to INTEGER) and put it into the picturebox - qr_pic.

private void button2_Click(object sender, EventArgs e)


            qr_pic.Image.Save(Application.StartupPath+@"\Code_" + DateTime.Now.ToString("d_MM_yy_HH_mm_ss") + ".png");


//Will save the generated qr code, to the same directory as your qr code app's exe file, and will name it

// CODE_[datestamp:timestamp].png (useful if you do a few in a row since it will not overwrite the codes unless you generate them 

// in intervals of less than a second.

private void qrlev_SelectedIndexChanged(object sender, EventArgs e)


            int caseSwitch = Convert.ToInt32(qrlev.Text);

            switch (caseSwitch)


               case  1:

               qrtext.MaxLength = 17;


                case 2:

               qrtext.MaxLength = 32;


                case 3:

               qrtext.MaxLength = 53;


                case 4:

               qrtext.MaxLength = 78;


                case 5:

               qrtext.MaxLength = 108;


                case 6:

               qrtext.MaxLength = 134;


                case 7:

               qrtext.MaxLength = 154;


                case 8:

               qrtext.MaxLength = 192;


                case 9:

               qrtext.MaxLength = 230;


                case 10:

               qrtext.MaxLength = 271;


                case 11:

               qrtext.MaxLength = 321;


                case 12:

               qrtext.MaxLength = 367;


                case 13:

               qrtext.MaxLength = 425;


                case 14:

               qrtext.MaxLength = 458;


                case 15:

               qrtext.MaxLength = 520;


                case 16:

               qrtext.MaxLength = 586;


                case 17:

               qrtext.MaxLength = 644;


                case 18:

               qrtext.MaxLength = 718;


                case 19:

               qrtext.MaxLength = 792;


                case 20:

               qrtext.MaxLength = 858;



            tlen.Text = qrtext.MaxLength.ToString();


// This function will, depending on what you select in the dropdown, limit the maximum length

//of the main text box, so your code corresponds to the level you selected.

// This ensures you CANNOT enter, for example, more than 17 characters for level 1 at low error correction (which is the max).

And that is it. You are done.

Your very own QR Code generator! YAY!

But, why the "part one" at the top? Because next time, I will go through superimposing your logo into the QR image on generation so your QRCodes will stand out. 

Step 5 Source Code

My Zipped Source (Includes QR Toolkit DLL).

Enjoy! And don't label your pets!



Awesome post! That's really cool, this is something that I didn't know how to do :p.

Thanks. This was originally part of a cmd-like program I created cause I hate windows CMD so friggin' much. Integrated a few basic commands as well as text to HEX, text to BIN, QR Code Gen, Pulling weather forecasts from googls, getting hardware info, ping, copying.. the works. Still in progress as this is one of those sand traps that I never seem to finish and they slowly become too big for me to even continue coding them... Too ambitious i suppose..

I have a somewhat off topic question, why C# ? I see people using C++, Java, Python… But not a lot of C#, what drew you to it?

A friend suggested it to me, I found it very similar to C++ and Java, so I gave it a try. Before C# I used to work in pascal (Delphi). Then when I started working in C#, I found it to my liking, more so than Delphi. Programming languages are easy to learn once you know at least one. It's the same logic, writtern a little differently. I am still trying to broaden my knowledge by learning as many as possible. Now that I feel at home with C#, I am starting to dabble in Java and JS, as well as setting my sights on python and html / php.

The only issue I have here is not having enough time.

There is NEVER enough time, haha.

Python is awesome, but it's like drugs. Once you start with that, you don't really want to do anything else..

I no can has life then...

Nope. Pretty much not. Then again I'm writing this from my physics class.. Perhaps you just need more multi-tasking?

not enough hours in the day. Between my 12 h a day desk job (7/7.30 to 6pm ) and travel time and mandatory husband + wife time, I do not have enough time.... BUT. There's sat and sunday i suppose.

many thanks for you
but i cant find dropdown and editbox
how i can find??

they should be located in the toolbox on the right side of the application.

no there is nothing

many thanks for you
i did it

dear Mr Falkreath
i want to ask u
i want to write code of decode the qr
can you pleas give me some hints and should i use same QR Toolkit or another library

hello mr falkreath
maximum how many characters do I enter? because my character's long (3000) or There may be more..
I get application error..
thank you

I do notice "// This function will, depending on what you select in the dropdown, limit the maximum length" In the code posted above. Is it an actual error you receive, or is the program saying you have done something invalid?

The number of characters : 228
and error message :
Index was outside the bounds of the array.

thank you

Hello, I have the same problem, any news about how to solve this issue?

I am Sory I gave the wrong image
right picture
I did change length

program UI

and error message
thank you

I arrive at an issue here.. I don't know what the Encode() function contains. Has it occurred to you that the highest previous max length (858) was chosen for a reason? As in… You can't change the max value to 2000 and have it work just like that?

Can I change the maximum value?

I have no idea. Like I said, I can't see inside the 'Encode()' function to see what it's doing.

Any chance you would take on a student?

hello, it's possible to use with visual studio 2012 for an application phone with sdk8?

I need to print QRCode from a Mainframe.
can you help me?
With source code or tips to build a component in C + +
I need to build an image with QRCode and insert it into PCL file
Thanks in advance


I downloaded your file and unzipped it. However, it didn't show anything when I double click grgen.sln. Can you tell me how to run the program?

Thanks a lot in advance.

Share Your Thoughts

  • Hot
  • Latest