Performing Handle-Based Operations

A handle is a unique number with which some element of the operating system is identified to the computer. For example, every window on your desktop has a unique handle that enables the computer to distinguish it from other windows. Every device context, brush, pen, and font also has a unique handle.

To maintain optimal compatibility with the Win32 API, the Graphics, Pen, Brush, and Font objects support handle-based operations. For example, if you use the Win32 CreatePen function to create a pen, this function returns a handle. You can then pass this handle to the Pen object constructor, and the object is created based on the characteristics of that Win32 pen.

Even if you do not create a Pen, Brush, or Font object based on a handle that you allocate, you can retrieve the handle on which a Pen, Brush, or Font object is based. Each of these objects supports both a copyHandle and a getHandle method, and once you’ve used these methods to duplicate or retrieve the object’s handle, you can pass that handle to any Win32 function that is intended to take such a handle as a parameter.

The following are a few important rules to keep in mind when performing handle-based operations with the Graphics object:


Note that while this example uses the handle to a device context, the principle illustrated here applies to pens, brushes, fonts, and bitmaps.