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:
Below is an example that illustrates appropriate handle management. This example uses the Win32 GetDC to retrieve the handle to the form’s device context, then creates a Graphics object based on that handle. After using the Graphics object to draw a line on the form, the Graphics object’s dispose method is used to destroy the Graphics object, and the Win32 ReleaseDC routine is used to free the device context handle allocated by GetDC:
// import the com.ms.wfc.Win32.Windows package.
import com.ms.wfc.win32.Windows;
int hDC = Windows.GetDC(this.getHandle());
Graphics g = new Graphics(hDC);
g.drawLine(new Point(0,0), new Point(100, 0));
g.dispose();
Windows.ReleaseDC(hDC);
Note that while this example uses the handle to a device context, the principle illustrated here applies to pens, brushes, fonts, and bitmaps.
Handles retrieved through the getHandle method are not copies of an object’s underlying handle. Therefore, you should never attempt to free handles retrieved through getHandle. Such handles are freed when the object is disposed.