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 . . .
}
|