Share via


How to: Draw Graphics on a Windows Form

This example draws a circle inside a square on a Windows Form. The following method defines the size, shape, and color of the circle and the square.

Example

private void DrawIt()
{
    System.Drawing.Graphics graphics = this.CreateGraphics();
    System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
       50, 50, 150, 150);
    graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
    graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
}

Compiling the Code

  1. In a Windows Forms application, paste the definition of method DrawIt in the Form1 partial class.

  2. In the Form1.cs[Design] window, add a Button to Form1.

  3. Double-click the button, and then add a call to DrawIt to the click event handler, button1_Click.

  4. Press F5 to run the program.

The following example shows the complete version of Form1.cs.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            DrawIt();
        }

        private void DrawIt()
        {
            System.Drawing.Graphics graphics = this.CreateGraphics();
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
                50, 100, 150, 150);
            graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
            graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
        }
    }
}

Security

To run this process, your assembly requires a permission level granted by the UIPermission Class. If you are running in a partial-trust context, the process might throw an exception because of insufficient permissions.

See Also

Concepts

Designing a User Interface in Visual C#

Other Resources

Drawing Text and Graphics

Visual C# Guided Tour

Change History

Date

History

Reason

August 2010

Added instructions and a complete code example.

Customer feedback.