Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Drawing with C#

A tutorial with examples of how to draw different things on a form using OnPaint.

On Tuesday, May 25th 2004 at 03:18 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.5 with 77 votes)
Contextual Ads
More C# Resources
Advertisement

In this tutorial We're going to play a little by drawing with C#.

Start a new Windows Application project. Leave the form's width and height unchanged, Visual C# .NET default (300 x 300 pixels).
We override OnPaint with the following code:


protected override void OnPaint(PaintEventArgs paintEvnt)
{
    // Get the graphics object
    Graphics gfx = paintEvnt.Graphics;
    // Create a new pen that we shall use for drawing the line
    Pen myPen = new Pen(Color.Black);
    // Loop and create a new line 10 pixels below the last one
    for(int i = 20; i < 250; i = i + 10)
    {
    gfx.DrawLine(myPen, 20, i, 270, i);
    }
}



The result is this:



Play with the code further and you'll see you can make some nice little squares making the form look like a checkerboard.
This can be done with the following code:


protected override void OnPaint(PaintEventArgs paintEvnt)
        {
            // Get the graphics object
            Graphics gfx = paintEvnt.Graphics;
            // Create a new pen that we shall use for drawing the line
            Pen myPen = new Pen(Color.Black);
            // Loop and create a horizontal line 10 pixels below the last one
            for(int i = 20; i <= 250; i = i + 10)
            {
                gfx.DrawLine(myPen, 20, i, 270, i);
            }
            // Loop and create a vertical line 10 pixels next to the last one
            for(int x = 20; x < 280; x = x + 10)
            {
                gfx.DrawLine(myPen, x, 20, x, 250);
            }
        }



Same as the first piece of code, just that now we also loop and create a vertical line 10 pixels next to the last one.

Rectangles



Try this code:


protected override void OnPaint(PaintEventArgs paintEvnt)
        {
            // Get the graphics object
            Graphics gfx = paintEvnt.Graphics;
            // Create a new pen that we shall use for drawing the line
            Pen myPen = new Pen(Color.Black);
            // Loop until the coordinates reach 250 (the lower right corner of the form)
            for(int i = 0; i < 250; i = i + 50)
            {
                // Draw a 50x50 pixels rectangle
                gfx.DrawRectangle(myPen, i, i, 50, 50);
            }
        }



Let's move to something more serious.


protected override void OnPaint(PaintEventArgs paintEvnt)
{
    // Get the graphics object
    Graphics gfx = paintEvnt.Graphics;
    int x1 = 0;
    int y1 = 0;
    // Loop trough the 255 values red can have
    for(int i = 0; i <= 255; i++)
    {
        // Create new brush with a defined color
        Color brushColor = Color.FromArgb(i, 0, 0);
        // The brush is solid because we want a solid rectangle
        SolidBrush myBrush = new SolidBrush(brushColor);
        // Actually draw the rectangle
        gfx.FillRectangle(myBrush, x1, y1, 10, 10);
        // The next rectangle should be near the last one
        x1 = x1 + 10;
        // If the row is complete start another one
        if((x1 % 290) == 0)
        {
            y1 = y1 + 10;
            x1 = 0;
        }
        }
        for(int i = 0; i <= 255; i++)
        {
        Color brushColor = Color.FromArgb(0, i, 0);
        SolidBrush myBrush = new SolidBrush(brushColor);
        gfx.FillRectangle(myBrush, x1, y1, 10, 10);
        x1 = x1 + 10;
        if((x1 % 290) == 0)
        {
            y1 = y1 + 10;
            x1 = 0;
        }
    }
    for(int i = 0; i <= 255; i++)
    {
    Color brushColor = Color.FromArgb(0, 0, i);
    SolidBrush myBrush = new SolidBrush(brushColor);
    gfx.FillRectangle(myBrush, x1, y1, 10, 10);
    x1 = x1 + 10;
    if((x1 % 290) == 0)
    {
        y1 = y1 + 10;
        x1 = 0;
    }
}


The above code produces the following:



The easiest way to learn is by examples and exercises. Therefore search for different results and try to accomplish something else by modifying the pieces of code or creating your own.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Hennie on Thursday, February 17th 2005 at 08:01 AM

Simple Tutorial, but very helpful. Thank you.

by nickeax on Sunday, May 8th 2005 at 03:17 AM

Thanks for this informative tute.

by Misko on Wednesday, November 23rd 2005 at 03:33 PM

More helpful than other tutorials where you can't see the purpose of the tutorials because of its complexity

by Hugh Wood on Tuesday, March 21st 2006 at 07:00 PM

Took me 40 minutes to find a tutorial on how to draw straight onto a form that I coudl either get to or understand, this does both brilliant.

by Hareen on Friday, May 5th 2006 at 04:59 AM

Simple and and easy. Good job!

by Mark on Monday, June 26th 2006 at 04:03 PM

Informative.. thanks. Provided what I was looking for.

by anonymous on Friday, August 11th 2006 at 07:08 PM

Very good. Even a beginner like me could understand this

by on Tuesday, March 6th 2007 at 01:41 PM

A very very beginner. Where does the OnPaint go?

by Andrei Pociu on Tuesday, March 6th 2007 at 03:39 PM

Inside the class of your main form (Form1 for example). It will override the existing OnPaint.

by Z247 on Tuesday, April 10th 2007 at 05:07 PM

Thank You

by tom c on Monday, May 21st 2007 at 04:45 PM

great tutorial. straight forward like all cide should be.

by Vikas Sihag on Wednesday, June 20th 2007 at 10:35 AM

That was a FABULOUS TUTORIAL
It easily poked into my garbage box(MIND).
;o

by eashwari on Tuesday, September 11th 2007 at 05:49 AM

Hi,
This is really very useful for beginners like me in graphics.
Thanku

by rahman on Thursday, November 1st 2007 at 07:39 AM

simple but much more informative

by Andrei on Thursday, November 29th 2007 at 04:22 AM

great tutorial! But I need something more complicated:(. I want to make a program that looks like Paint! I want to draw rectangles, lines and other shapes with mouse. Can anybody help me?

by Ehab on Thursday, December 20th 2007 at 05:23 AM

Nice straightforward tutorial.. I noticed little bug,, the last for loop in the entire code needs a curly bracket ( } ) to close it,, correct me if am wrong :)
great work Andrei
Shokran, Gracias, Thanks
Ehab

by red on Friday, December 28th 2007 at 11:05 AM

very good example code...

by Rafael Espericueta on Saturday, January 5th 2008 at 09:05 PM

I can\'t get any of this to run.

I get the error message:

The type of namespace name \'PaintEventArgs\' could not be found (are you missing a using directive or an assembly reference?

The usual frustration I have is that lots of details are given on stuff that would be easy to figure out, and no mention of the ESSENTIAL information without which one can do nothing. Where can one go to REALLY learn this stuff?

by Andrei Pociu on Saturday, January 5th 2008 at 10:36 PM

PaintEventArgs is in System.Windows.Forms. As long as you have an using statement for that (and since it's a Windows Forms application, you should) everything should work. What version of .NET are you trying to compile this into and what is the project type?

by omnimny on Monday, February 11th 2008 at 11:36 AM

Hello,
I changed little the code in the way to show it as a graph paper, as shown below, and added A.minscroll property in the form right to w.800, and setting i

by omnimny on Monday, February 11th 2008 at 11:50 AM

sorry, add background color white in the properties, too. :)

by Chuck on Saturday, April 19th 2008 at 10:42 PM

I noticed when drawing on say for example a panel control, the scrollbars will not display when the content exceeds the viewable drawing area. How do you overcome this?

by Chuck on Saturday, April 19th 2008 at 10:47 PM

Hey ominimny, I think you can use g.TranslateTransform(_page.AutoScrollPosition.X, _page.AutoScrollPosition.Y);


...but I can't be sure since I can't even get scroll bars to show up when I paint music staff lines on my panel control.

by Chuck (again) on Sunday, April 20th 2008 at 02:29 AM

Ok...I got it and thought I would share with the community.

Issue: Draw lines using graphics. Lines exceed the viewable area but scrollbars do not display.

Setup: using System.Windows.Forms.TabPage to draw on. My Form creates a control that allows me to set parameters of an object I call Staff (used to create musical staff lines). Once these parameters are defined for the staff object, the control does a call back (using a delegate) to the main form that created this control, informing it that the CreateStaff button was clicked. This delegate will call a method to Invalidate the TapPage control which causes it to paint. The paint method calls a draw method on the composition object which executes the DrawStaff ie: Graphics g = PaintEventArgs.Graphics;

Challenge: Many...but, the one specific to this thread is the scrollbar. First have AutoScroll = true and AutoScrollMinSize will be set in code at run time. Now, as I draw new staff lines I increment this AutoScrollMinSize value like this: DrawCanvas.AutoScrollMinSize = new Size(var1,var2);
var1 and var2 increase as I add more staff lines. Now, scrolling made everything disapear so I added g.TranslateTransform(DrawCanvas.AutoScrollPosition.X, DrawCanvas.AutoScrollPosition.Y);

Now everything works fine. If you want the code just email me because its to much to put here.

Keys to remember:
Graphics TranslateTransform
Paint method and using the PaintEventArgs
AutoScroll = true and DrawCanvas.AutoScrollMinSize = new Size(var1,var2);

by Si on Tuesday, April 22nd 2008 at 05:39 AM

Good tutorial but I'd like to know how to draw an object of a class I have created on the form and then move it.

E.g. say I have a class called Ball and I'd like to draw an object of this class on the form and then move it horixontally. Where can I find how to do this??

by Umasankar on Wednesday, April 30th 2008 at 12:28 AM

Hi,

I am umasankar padhan greatful for this line designing.

My request is i want to Draw aline from croners of the Windows Form using c# (gui) or (cui).So; You will give me this report and reference of codes through my Email.

by Donna on Friday, July 11th 2008 at 01:31 AM

Can you show how to draw with the mouse onto a surface in the browser in C#?

by robinop on Wednesday, July 23rd 2008 at 04:54 AM

Pls help,
I would like to create a object called "POINT" and let the user to manipulate with it.
It means: implement event

by kamran on Wednesday, July 23rd 2008 at 03:41 PM

i want to draw two arrows using paint.
i have 2 button
when i click first button one arrow is vissibe other is invisible
when i click second button other arrow is vissibe first is invisible

by Donna on Thursday, July 24th 2008 at 12:07 PM

Can you show how to draw with the mouse onto a surface in the browser in C#?

I'm programming in ASP.NET.

Thanks!

by Oliver on Monday, October 6th 2008 at 11:00 AM

protected override void OnPaint(PaintEventArgs e)
{
// Get the graphics object
Graphics gfx = paintEvnt.Graphics;***
// Create a new pen that we shall use for drawing the line
Pen myPen = new Pen(Color.Black);
// Loop and create a new line 10 pixels below the last one
for (int i = 20; i < 250; i = i 10)
{
gfx.DrawLine(myPen, 20, i, 270, i);
}

***Where the three stars are paintEvnt is red underligned and it dose not exist because i have not declaired it...i think, im not sure, im new to C# and everything else works apart from that. if i have to declair it, how is it like a vairiable e.g:
int[] kablamao = new int;
kablamao = new int [3];
kablamao[0] = 666;
:P

by Donna on Monday, October 6th 2008 at 06:00 PM

I need to be able to do something like this in a browser.

Can you explain how this might work there?

by thankyou on Monday, November 17th 2008 at 05:30 PM

Thanks for all this!! What the fuck is wrong with MSDN? Almost all the info there seems useless.

by shada ahmed on Saturday, May 9th 2009 at 04:29 AM

drawing waveform

by shada ahmed on Saturday, May 9th 2009 at 04:32 AM

drawing waveform

by riya on Thursday, May 21st 2009 at 12:00 PM

i get to compile the code without any errors but i dont get any output, can someone pls HELP me its important. I am using Visual c# 2005. plsssss

by Mike on Friday, June 12th 2009 at 09:45 PM

protected override void OnPaint(PaintEventArgs e)
{
// Get the graphics object
Graphics gfx = paintEvnt.Graphics;***
// Create a new pen that we shall use for drawing the line
Pen myPen = new Pen(Color.Black);
// Loop and create a new line 10 pixels below the last one
for (int i = 20; i < 250; i = i 10)
{
gfx.DrawLine(myPen, 20, i, 270, i);
}

***Where the three stars are paintEvnt is red underligned and it dose not exist because i have not declaired it...i think, im not sure, im new to C# and everything else works apart from that. if i have to declair it, how is it like a vairiable e.g:
int[] kablamao = new int;
kablamao = new int [3];
kablamao[0] = 666;

------------------------------------------------

The object paintEvnt is the argument passed to the OnPaint event handler, but you have it named e in the definition. Rename it, like so:

protected override void OnPaint(PaintEventArgs paintEvnt)
{
// Get the graphics object
Graphics gfx = paintEvnt.Graphics;

by mute on Friday, July 31st 2009 at 05:04 AM

Good tutorial. How would you make this happen when you pressed a button on the form for example? Rather than when the form is created?

Cheers

by pandiyan on Monday, August 31st 2009 at 02:49 AM

Thank you,it's very usefull for me

by sahar on Monday, October 26th 2009 at 03:30 AM

hi i need to draw graph in c# on run time.
Can you explain how this might work there?

by svs on Saturday, November 7th 2009 at 10:45 AM

hi, how can run with button ? I tried but i couldn^t call function

by nev on Saturday, April 17th 2010 at 08:04 PM

Hi...how do I change the pen style?
I tried this
Pen p=new Pen(Color.Red);
p.DashStyle=DashStyle.Dot;
But I am getting an error:The name DashStyle does not exist in the current context.

by RealBuga on Monday, May 3rd 2010 at 12:17 PM

Hi Nev:
Solution is:
using System.Drawing.Drawing2D;

by John Gates on Wednesday, June 9th 2010 at 03:27 AM

Easy stuff

by grrr on Wednesday, June 30th 2010 at 09:30 AM

I did exactly as the tutorial said, it compiled fine, and my form is still blank.

by Ashwin on Monday, October 4th 2010 at 05:40 AM

Brilliant Stuff in here .. terse and to the point !!

Thanks man.

by http://pickatutorial.com on Monday, October 11th 2010 at 12:18 PM

A difficult subject explained in an easy tutorial. Thanks.

by Some guy on Tuesday, November 30th 2010 at 09:43 AM

I believe you want to include the base method when overriding methods.

protected override void OnPaint(PaintEventArgs paintEvnt)
{
...
base.OnPaint(paintEvnt)
}

In this example you would not need it because you are handling everything that is painted yourself but it is still good practice to include it. Is there some reason for not including it that I am missing?

by Masooda on Wednesday, January 19th 2011 at 02:33 AM

I need coding for drawing a star in visual c#.

by pushpika on Tuesday, January 25th 2011 at 12:02 AM

great work

by Besart on Saturday, March 5th 2011 at 03:15 PM

Hi, I really like it, please can you sent source code to me, or post here.

Thank you

by khongor on Sunday, March 20th 2011 at 03:57 AM

how to make panit and panel to import images. so
image save ... help me

by epic fail on Tuesday, March 22nd 2011 at 10:39 PM

wtf, i couldnt make anyhtign work, so i jsut copied the code in exactly how he had it and i just got error message spam, why...
I am using visual basic 2010 C#

by code on Saturday, April 9th 2011 at 10:19 AM

thanks man you helped me very much
bless you and bless your faithful job

by How to stop notification on Thursday, June 2nd 2011 at 02:13 AM

What should I do to stop receive notification
to my e-mail, about this tutorial?

by Cindy on Wednesday, June 8th 2011 at 10:59 PM

Hi. Thanks for the tutorial. I found it fun to do and it was a good destressor when my other programming study was not going so well. It was clear and easy to understand

by ABDULAZIZ ALGHAMDI on Monday, October 10th 2011 at 07:35 PM

THANKYOU VERY VERY VERY MUTCH

by ABDULAZIZ ALGHAMDI on Monday, October 10th 2011 at 07:36 PM

THANKYOU VERY VERY VERY MUTCH

by magazine subscriptions to Germany on Monday, December 12th 2011 at 04:51 AM

thank u for providing me information on List View.
I want to know how i can display data in datalist in Newsletter layout and Thank you so much, this is easy to understand and fun to continue along with. I am a migrating VB.NET/C# Developer looking for an insight into VC .NET. I've found the VC tutorials on many sites to be confusing, and the navigation around the sites to be near impossible to use! Thanks once again.

by magazine subscriptions to Japan on Monday, December 12th 2011 at 04:54 AM

thank u for providing me information on List View.
I want to know how i can display data in datalist in Newsletter layout and Thank you so much, this is easy to understand and fun to continue along with. I am a migrating VB.NET/C# Developer looking for an insight into VC .NET. I've found the VC tutorials on many sites to be confusing, and the navigation around the sites to be near impossible to use! Thanks once again.

by on Monday, January 9th 2012 at 05:20 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by Addison on Monday, January 9th 2012 at 05:31 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by gdpoker on Saturday, January 21st 2012 at 06:40 PM

I am glad for writing to let you be aware of of the wonderful discovery my princess obtained visiting the blog. She mastered a lot of pieces, which include how it is like to possess an awesome helping mindset to have many more just fully understand certain multifaceted matters. You undoubtedly exceeded our desires. Thank you for producing the priceless, safe, edifying as well as unique tips on the topic to Sandra.

by Marco Island Homes For Sale on Sunday, February 5th 2012 at 10:26 PM

I don’t even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you're going to a famous blogger if you are not already ;) Cheers!

by Marco Island real Estate Blog on Sunday, February 5th 2012 at 10:31 PM

You could certainly see your enthusiasm within the paintings you write. The sector hopes for more passionate writers such as you who aren't afraid to say how they believe. All the time follow your heart.

by cheap writing services on Wednesday, March 7th 2012 at 01:11 PM

Thanks for all this!! What the fuck is wrong with MSDN? Almost all the info there seems useless.

by http://www.collegepersonalstatement.net college personal statement on Wednesday, March 7th 2012 at 01:20 PM

even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you're going to a famous blogger if you are not already ;) Cheers!

by med school personal statement on Monday, March 19th 2012 at 06:06 AM

Thanks for all this!! What the fuck is wrong with MSDN? Almost all the info there seems useless.

by signs manchester on Saturday, April 21st 2012 at 09:02 AM

Almost all the info there seems useless.

by AZIZ on Thursday, May 10th 2012 at 11:38 AM

how i can draw many sommets

by AZIZ on Thursday, May 10th 2012 at 11:38 AM

how i can draw many sommets

by AZIZ on Thursday, May 10th 2012 at 11:38 AM

how i can draw many sommets

by AZIZ on Thursday, May 10th 2012 at 11:38 AM

how i can draw many sommets

by AZIZ on Thursday, May 10th 2012 at 11:38 AM

how i can draw many sommets

by AZIZ on Thursday, May 10th 2012 at 11:38 AM

how i can draw many sommets

by AZIZ on Thursday, May 10th 2012 at 11:40 AM

how i can draw many sommets

by montreal web design company on Sunday, July 29th 2012 at 11:15 PM

Because of its complexity this tutorial is very helpful. I made this one in my programming subject, using codes to create a line or anything. This is a brilliant stuff! Visiting your blogs will help me in advance for my lesson.



by resume writing services reviews on Thursday, August 23rd 2012 at 02:12 AM

Thanks for the great buttons.resume writing services reviews First-class job. http://www.resumewritingservicesreviews.net

by resume writing services reviews on Thursday, August 23rd 2012 at 02:12 AM

Thanks for the great buttons.resume writing services reviews First-class job. http://www.resumewritingservicesreviews.net

by resume writing services reviews on Thursday, August 23rd 2012 at 02:12 AM

Thanks for the great buttons.resume writing services reviews First-class job. http://www.resumewritingservicesreviews.net

by resume writing services reviews on Thursday, August 23rd 2012 at 02:12 AM

Thanks for the great buttons.resume writing services reviews First-class job. http://www.resumewritingservicesreviews.net

by robin on Thursday, August 23rd 2012 at 04:02 AM

very nice

by ipad apps for kids on Tuesday, October 2nd 2012 at 03:24 AM

I made this one in my programming subject, using codes to create a line or anything.

by loans on Thursday, October 18th 2012 at 05:10 AM

I strictly recommend not to hold off until you get enough cash to order different goods! You should just get the loans or financial loan and feel comfortable

by food storage bags on Thursday, October 25th 2012 at 03:35 AM

You should just get the loans or financial loan and feel comfortable

by mre meals for sale on Thursday, November 1st 2012 at 05:54 AM

You should just get the loans or financial loan and feel comfortable

by invisible dog fence wire on Saturday, November 3rd 2012 at 06:41 AM

Ive read anything comparable to this prior to. So nice to uncover somebody with several original applying

by invisible fence wire on Tuesday, November 6th 2012 at 01:06 AM

comparable to this prior to. So nice to uncover somebody with several original applying

by food g on Wednesday, November 7th 2012 at 05:02 AM

You should just get the loans or financial loan and feel comfortable

by Margahayuland on Sunday, June 9th 2013 at 07:29 AM

Start a new Windows Application project. Leave the form's width and height unchanged
http://sooboos.com/margahayuland/margahayuland-42-tahun-membangun-ruang-hidup.php
http://sooboos.com/situs-berita/penting-panas-perlu-dan-seruu.php
http://sooboos.com
http://wadahpromoindonesia.blogspot.com/2013/05/margahayuland-42-tahun-membangun.html
http://tech-kinodeon.blogspot.com/2013/02/agen-bola-ligabet88-promo-bonus-100.html
http://tech-kinodeon.blogspot.com/2013/04/penting-panas-perlu-dan-seruu.html
http://tech-kinodeon.blogspot.com/2013/05/korek-api-gas-fighter-indonesia.html


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources