Working with Window Handles

The base Control class encapsulates a Win32 HWND (handle) through a private member that extends com.ms.wfc.app.Window. The Window class manages the subclassing of the window procedure for the HWND created for your control.

Whenever you request a handle with a call to Control.getHandle, the handle is created if needed or returned if it exists. When the handle is created, the Control class first calls the getCreateParams method to determine the correct window styles for creating the handle. If you want to specify window styles or extended window styles, you can override the getCreateParams method. Immediately after the handle is created, the createHandle event is fired. The destroyHandle event is fired immediately before the handle is destroyed. The handle is therefore valid during both the create and destroy handle events.

The lifetime of any given handle is determined by the implementation of your control. However, the lifetime of an instance of any control is not tied to the lifetime of a handle.

WFC allows you to manipulate controls in various ways that might require that the control be recreated in Windows. For example, you might be working with a control such as a ruler. When you change the ruler's units, this might result in the control being recreated, invalidating the HWND, as in the following example:

{
h = x.getHandle();
x.units = "points";   // change property that results in recreation
// h is now invalid
}

As a rule, it is safest when using a handle to get it immediately before using it.

You can request that your handle be recreated (destroyed and then immediately created again) by calling the recreateHandle method. If the recreateHandle method is called, then getRecreatingHandle will return true until the handle is created again. This allows you to place special logic in the destroyHandle event that retrieves state from the HWND during handle recreation. An example is a list box, where you might want to save all the items from the list box upon handle destruction if the handle is being recreated. If you need the window styles reapplied to the window, but you don’t need the handle to be recreated, you can call updateStyles. This will call the getCreateParams method and reapply the style and extended style to the HWND.

Note that calling these functions will do nothing if the handle has not been created. This is useful in property setting methods, because you don't want to force handle creation, but might need to change the HWND if it has already been created. By convention, you should not force handle creation for simple property changes. Forcing handle creation early can be expensive because the user might set other properties that might require handle recreation. It is best to require handle creation only to show a control visually, but not to adjust the properties.