This tutorial shows you how to draw a graphic in windows forms application using c# code.

To play the demo, you should create a new windows forms project, then drag a button from the visual studio toolbox to your winforms.

To draw a line, you can add code to handle the button click event as the following code.

private void button1_Click(object sender, EventArgs e)
{
     System.Drawing.Graphics g = this.CreateGraphics(); 
     Pen p = new Pen(System.Drawing.Color.Red, 5); 
     g.DrawLine(p, 10, 10, 100, 10);
}

If you want to draw a rectangle you can add the code Paint event handler as shown below.

private void Form1_Paint(object sender, PaintEventArgs e)
{
     System.Drawing.Graphics g = this.CreateGraphics(); 
     Pen pen = new Pen(System.Drawing.Color.Blue, 5); 
     Rectangle rec = new Rectangle(0, 0, 100, 50); 
     g.DrawRectangle(pen, rec);
}

Our last example, we'll create another rectangle with a dotted line stroke.

private void button1_Click(object sender, EventArgs e)
{
     System.Drawing.Graphics g = this.CreateGraphics(); 
     Pen pen = new Pen(System.Drawing.Color.Blue, 5); 
     pen.DashPattern = { 2, 2, 2, 2 }; 
     Rectangle rec = new Rectangle(0, 0, 100, 50); 
     g.DrawRectangle(pen, rec);
}