Components Notebook
Home

Notebooks
C#
C++
Agile Hacker
Hardware
Photos

Book Reviews

Drawing On A Form

This is a simple example to help anyone just getting started with graphics programming using GDI+ in .NET, using SharpDevelop.

Create a C#, Windows Application Project.

In the Properties window for your Form, set the BackColor. I use White for my drawing surface. You can also change the Text property to set the message on the Window's control bar.

Since this is our first .NET graphics program, we need to figure out where we should put our drawing code and what some drawing commands are. Take a look at the code generated by the wizard when you created the project. You have the line: public class MainForm : System.Windows.Forms.Form which is defining the class MainForm which inherits from System.Windows.Forms.Form. Take a look in the help window in the top right corner of SharpDevelop. Look in the .NET Framework Library Reference. Find the section for System.Windows.Forms, then find the Form class. If you look through the Form members you will find the Paint event under Public Events. If you keep looking you will find the OnPaint method under Protected Methods. Lets use OnPaint for this example.

In the online help for the OnPaint method click on PaintEventArgs to find out what is being passed to OnPaint. One of the Properties for the PaintEventArgs class is a Graphics object. The Graphics class is found in the System.Drawing namespace. By looking through the documentation for the Graphics members you will find many methods that are useful for drawing on the Form.

Now that we know there is an OnPaint function, and what the methods for the Graphics class are, lets add code to override the OnPaint function in your Form class and try it out.

protected override void OnPaint( PaintEventArgs pe )
{
   Graphics g = pe.Graphics;
   Pen myPen = new Pen( Color.Blue, 2 );
   g.DrawLine( myPen, 10, 10, 210, 210 );
   g.DrawLine( myPen, 10, 210, 210, 10 );
   g.DrawEllipse( myPen, 50, 50, 200, 100 );
   myPen.Dispose();
} 

Here is a screen shot showing the results.

Now you know how to draw on a form. Read the documentation for the various drawing methods, and play with the code in the OnPaint method to see what you can come up with.

C# Notebook


wburris at telusplanet dot net