Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » The Basics of Drawing Graphics onto Windows Forms

The Basics of Drawing Graphics onto Windows Forms

This article gives you an explanation of the use of the GDI+ library and how the .NET base classes can enhance graphics.

Technologies: .NET 1.0/1.1, GDI+,Visual C# .NET
Total downloads :
Total page views :  12296
Rating :
 4.5/5
This article has been rated :  4 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor


Related EbooksTop Videos

Introduction:

GDI+ consists of the set of .NET base classes that are available to control custom drawing on the screen. These classes arrange for the appropriate instructions to be sent to the graphics device drivers to ensure the correct output is placed on the screen. GDI provides a level of abstraction, hiding the differences between different video cards. You simply call on the Windows API function to do the specific task, and internally the GDI figures out how to get the client's particular video card to do whatever it is you want when they run your particular piece of code.

Not only this, but the client has several display devices - for example - monitors and printers - GDI achieves the task of making the printer look the same onscreen as far as the application is concerned. If the client wants to print something instead of displaying it, your application will simply inform the system that the output device is the printer and then call the same API functions in exactly the same way. As you can see, the device-context (DC) object is a very powerful mechanism. Having said that, we can also use this layer of abstraction to draw onto a Windows Form. This paper will therefore begin with an example of a  basic Windows Forms development in order to demonstrate how to draw graphics onto a Windows Form, or a control on that form. The focus of this article will be on graphics.

The Form object is used to represent any Window in your application. When creating a main window, you must follow two mandatory steps:

  1. Derive a new custom class from System.Windows.Forms.Form
  2. Configure the application's Main() method to call System.Windows.Forms.Application.Run(), passing an instance of your new Form derived as a class argument.

Here is an example:
 
C# File: MyForm.cs

using System;

using System.Windows.Forms;

public class MyForm : System.Windows.Forms.Form

{

    public MyForm()

    {

        Text = "No Graphics";

    }

    public static void Main()

    {

        Application.Run(new MyForm());

    }
}

To compile:

C:\Windows\Microsoft.NET\Framework\v2.050727>csc /target:winexe MyForm.cs

So now we have a blank form. So what do we do to learn how to use graphics? If you use Visual Studio 2005 you probably know that the .NET Framework 2.0  supports partial classes. With Visual Studio 2005, a Windows Form is completely defined with a single C# source file. The code generated by the IDE was separated from your code by using regions, therefore taking advantage of partial classes.

By default, each form named Form111 corresponds to two files; Form111.cs which contains your code and Form111.Designer.cs, which contains the code generated by the IDE. The code, however, is usually generated by dragging and dropping controls. One of the simplest uses for the System.Drawing namespace is specifying the location of the controls in a Windows Forms application. More to the point, user-defined types are often referred to as structures.

To draw lines and shapes you must follow these steps:

  1. Create a Graphics object by calling System.Windows.Forms.Control.CreateGraphics method. The Graphics object contains the  Windows DC you need to draw with. The device control created is associated with the display device, and also with the Window.
  2. Create a Pen object
  3. Call a member of the Graphics class to draw on the control using the Pen

Here is an example of a Form with a line drawn at a 60 degree angle from the upper-most left hand corner:

//File: DrawLine.cs
 

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

public class MainForm : System.Windows.Forms.Form

{

    private System.ComponentModel.Container components;

 

    public MainForm()

    {

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true); 

    } 

 

    //  Clean up any resources being used.

 

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    }

    #region Windows Form Designer generated code

 

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Fun with graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion 

 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

 

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    {

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

        // create  a  pen object with which to draw

        Pen p = new Pen(Color.Red, 7);  // draw the line 

        // call a member of the graphics class

        g.DrawLine(p, 1, 1, 100, 100);

    }

    private void Form1_Resize(object sender, System.EventArgs e)

    {

        // Invalidate();  See ctor!

    }

}
 
TO COMPILE:

csc.exe /target:winexe DrawLine.cs
 
Typically, you specify the Pen class color and width in pixels with the constructor. The code above draws a 7-pixel wide red line from the upper-left corner (1,1,) to a point near the middle of the form (100, 100).  Note the following code that draws a pie shape:
                 
File:// DrawPie.cs
                    

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

 

 

public class MainForm : System.Windows.Forms.Form

{

    private System.ComponentModel.Container components;

 

    public MainForm()

    { 

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true); 

    }

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    }
 

    #region Windows Form Designer generated code

    //

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Fun with graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion
 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

 

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    { 

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

        Pen p = new Pen(Color.Blue, 3);

        g.DrawPie(p, 1, 1, 100, 100, -30, 60);

    }

    private void Form1_Resize(object sender, System.EventArgs e)

    {

    }

}

To compile:

csc.exe /target:winexe DrawPie.cs

A structure, or "struct", is a cut-down class that does almost everything a class does, except support inheritance and finalizers. A structure is a composite of other types that make easier to work with related data. The simplest example is  System.Drawing.Point, which contain X and Y integer properties that define the horizontal and vertical coordinates of a point.

The Point structure simplifies working with coordinates by providing constructors and members as follows:

// Requires reference to System.Drawing

// Create point

System.Drawing.Point p = new System.Drawing.Point(20, 20);

// move point diagonally

p.Offset(-1, -1)

Console.WriteLine("Point X {0}, Y {1}", p.X, p.Y.);

So as the coordinates of a point define its location, this process also specifies a control's location. Just create a new Point structure by specifying the coordinates relative to the upper-left corner of the form, and use the Point to set the control's Location property.

Graphics.DrawLines, Graphics.DrawPolygons, and Graphics.DrawRectangles accept arrays as parameters to help you draw more complex shapes:

Here is an example of a polygon, but with its contents filled. Notice the code responsible for filling the shape:

DrawPolygonAndFill.cs
                    

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data; 

 

public class MainForm : System.Windows.Forms.Form

{

    private System.ComponentModel.Container components;

 

    public MainForm()

    {

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true);

    }

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    } 

 

    #region Windows Form Designer generated code

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Fun with graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion

 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    {

 

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

        Brush b = new SolidBrush(Color.Maroon);

        Point[] points = new Point[]
        
{
            new Point(10, 10),

            new Point(10, 100),

            new Point(50, 65),

            new Point(100, 100),

            new Point(85, 40)};   // Notice the braces, as used in structures

            g.FillPolygon(b, points);

        }

    private void Form1_Resize(object sender, System.EventArgs e)

    {

    }

}  

Customizing Pens:

The color and size of a pen is specified in the Pen constructor, so you can manipulate the pattern and the endcaps. The endcaps are the end of the line, and you can use them to create arrows and other special effects. While pens by default draw straight lines, their properties can be set to one of these values: DashStyle.Dash, DashStyle.DashDot, DashStyle.DashDotDot, DashStyle.Dot, or DashStyle.Solid. Consider this final example:

UsePen.cs
                   

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

public class MainForm : System.Windows.Forms.Form

{

    private System.ComponentModel.Container components;

 

    public MainForm()

    { 

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true); 

    } 

 

    //  Clean up any resources being used.

 

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    } 

 

    #region Windows Form Designer generated code

 

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Learning graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion 

 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

 

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    { 

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

        // create a Pen object

        Pen p = new Pen(Color.Red, 10);

        p.StartCap = LineCap.ArrowAnchor;

        p.EndCap = LineCap.DiamondAnchor;

        g.DrawLine(p, 50, 25, 400, 25);

 

        p.StartCap = LineCap.SquareAnchor;

        p.EndCap = LineCap.Triangle;

        g.DrawLine(p, 50, 50, 400, 50);

 

        p.StartCap = LineCap.Flat;

        p.EndCap = LineCap.Round;

        g.DrawLine(p, 50, 75, 400, 75);

 

        p.StartCap = LineCap.RoundAnchor;

        p.EndCap = LineCap.Square;

        g.DrawLine(p, 50, 100, 400, 100);

    }

    private void Form1_Resize(object sender, System.EventArgs e)

    {

        // Invalidate();  See ctor!

    }

}
 
The basics underlying principles in this paper indicate the location and size of points so that they for a line or a shape. This should the new developer to understand that these principles can be expanded upon to specify the size and location of controls that are dragged and dropped onto a Windows Form. For instance, if we were to start Visual Studio 2005 and begin a Forms application, we could set that Form background color to white. The designer file and the source file that comprise the application would both reflect that property: the setting of the property would cause the IDE to generate the code in the Form.Designer.cs file. Well, that all for now. 

DrawLine.cs
            

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data; 

 

public class MainForm : System.Windows.Forms.Form

{ 

    private System.ComponentModel.Container components; 

    public MainForm()

    { 

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true); 

    } 

 

    //  Clean up any resources being used.

 

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    }
 

    #region Windows Form Designer generated code

 

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Learning graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion 

 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

 

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    { 

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

 

        // create  a  pen object with which to draw

        Pen p = new Pen(Color.Red, 7);

 

        // draw the line  

        g.DrawLine(p, 1, 1, 100, 100);

    }
 

    private void Form1_Resize(object sender, System.EventArgs e)

    {

        // Invalidate();  See ctor!

    }

}


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Dave
I have been studying the .NET Framework and the C# language for around a year. My first experience with programming was learning MS DOS DEBUG. I am about at an intermediate level with the CLR and the JVM. I am self taught and in need of tutorials to clarify the structure of C#, Vb, and other language programs.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved