The main object on which you will perform the drawings is called a graphic. In most cases, this object is not readily available when you need it: you must request it from the object on which you want to draw or you must create it. Both operations are highly easy.
In GDI+, a graphic object is based on a class called Graphics. This class is defined in theSystem.Drawing namespace. Before drawing, you should obtain a graphic object. Fortunately, every Windows control, that is, every object based on the Control class, automatically inherits a method called CreateGraphics(), which gives you access to the graphic part of a control. The syntax of theControl.CreateGraphics() method is:
public Graphics CreateGraphics();
As you can see, the CreateGraphics() method returns the Graphics object of the variable you call it from. Here is an example of getting the Graphics object of a form:
private void button1_Click(object sender, EventArgs e)
{
Graphics graph = CreateGraphics();
}
Another technique you can use to get the Graphics object of a control is to call theGraphics.FromHwnd() static method. Its syntax is:
public static Graphics FromHwnd(IntPtr hwnd);
Remember that this method is static. The argument passed to it must be a handle to the object whoseGraphics object you want to access. Every Windows control has a handle called Handle. Here is an example of using it to get the Graphics part of a form:
private void button1_Click(object sender, EventArgs e)
{
Graphics graph = Graphics.FromHwnd(this.Handle);
}
If you are using the Paint event of a window, it provides a readily available Graphics object from itsPaintEventArgs argument. You can access the Graphics object as follows:
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics . . .
}
As mentioned above, before drawing, make sure you have a Graphics object, which depends on your approach to drawing. To actually perform the drawing, the Graphics class provides various methods adapted for different shapes. Each method used to draw something has a name that starts with Draw... Also, each method that is used to draw a known shape requires a Pen argument. Therefore, when drawing, your first decision will be based on the shape or type of figure you want to draw.
Two other pieces of information are particularly important with regards to any figure or shape you will need to draw: its location and dimensions.
To keep track of the various drawings, the object on which you draw uses a coordinate system that has its origin (0, 0) on its top-left corner. If you are drawing on a form, this origin is positioned just under the title bar to the left:
How you specify the values of the starting point of a shape or figure depends on the shape.