Graphic Objects

Windows provides a variety of drawing tools to use in device contexts. It provides pens to draw lines, brushes to fill interiors, and fonts to draw text. MFC provides graphic-object classes equivalent to the drawing tools in Windows. The table below shows the available classes and the equivalent Windows graphics device interface (GDI) handle types.


For more information, see the GDI+ SDK documentation.

This article explains the use of these graphic-object classes:

Classes for Windows GDI Objects

Class Windows handle type


The class CImage provides enhanced bitmap support.

Each graphic-object class in the class library has a constructor that allows you to create graphic objects of that class, which you must then initialize with the appropriate create function, such as CreatePen.

Each graphic-object class in the class library has a cast operator that will cast an MFC object to the associated Windows handle. The resulting handle is valid until the associated object detaches it. Use the object's Detach member function to detach the handle.

The following code casts a CPen object to a Windows handle:

CPen myPen;
myPen.CreatePen(PS_COSMETIC, 1, RGB(255, 255, 0));
HPEN hMyPen = (HPEN)myPen;

To create a graphic object in a device context

  1. Define a graphic object on the stack frame. Initialize the object with the type-specific create function, such as CreatePen. Alternatively, initialize the object in the constructor. See the discussion of one-stage and two-stage creation, which provides example code.

  2. Select the object into the current device context, saving the old graphic object that was selected before.

  3. When done with the current graphic object, select the old graphic object back into the device context to restore its state.

  4. Allow the frame-allocated graphic object to be deleted automatically when the scope is exited.


If you will be using a graphic object repeatedly, you can allocate it once and select it into a device context each time it is needed. Be sure to delete such an object when you no longer need it.

What do you want to know more about

See also

Window Objects