Home

GDI+: The Graphics Object

 

Introduction

The main object on which you will perform most 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.

Getting a Graphic Object

In GDI+, a graphic object is based on a class called Graphics. This class is defined in the System::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 the Control::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:

System::Void button1_Click(System::Object ^  sender,
			   System::EventArgs ^  e)
{
    Graphics ^ graph = this->CreateGraphics();
}

Another technique you can use to get the Graphics object of a control is to call the Graphics::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 whose Graphics 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:

System::Void button1_Click(System::Object ^  sender,
			   System::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 its PaintEventArgs argument. You can access the Graphics object as follows:

System::Void Form1_Paint(System::Object ^  sender,
			 System::Windows::Forms::PaintEventArgs ^  e)
{
    e->Graphics . . .
} 
 

Previous Copyright © 2007-2013, FunctionX Home