How To Draw on a Memory Bitmap in GDI+


Summary


You may sometimes want to obtain a bitmap or image that contains the image that was drawn by a graphics object.

One of the overloaded constructors for the Bitmap class takes a graphics object as a parameter. However, this constructor does not use the image drawn by the graphics object to initialize the bitmap bits. It simply creates a bitmap with properties similar to the graphics object, such as dots per inch.

More Information


Because the Bitmap constructor does not initialize the image bits by using the image from the graphics object, code like the following will NOT result in a bitmap that contains the image that was drawn by the Graphics object:

Graphics g( hWnd );
// Draw on g
Bitmap b( 100, 100, &g ); // Will not get image from g

To use a graphics object to draw on a bitmap, code like the following can be used instead:
Bitmap b(100,100);
Graphics *g = Graphics::FromImage(&b);
// Draw on g

To capture the preexisting image from a window, a Windows Graphics Device Interface (GDI) function such as BitBlt() or StretchBlt() would have to be used to copy the image from the screen to a memory bitmap. This memory bitmap could then be used in the overloaded Bitmap constructor, which takes an HBITMAP as a parameter.

References


For additional information on capturing the screen using GDI, click the article number below to view the article in the Microsoft Knowledge Base:

186736 How To Capture and Print an Entire Window
"Capturing an Image" in the GDI section of the Platform SDK Documentation: