Subclassing a Window

To subclass an instance of a window, call the SetWindowLong function and specify the handle of the window to subclass the GWL_WNDPROC flag and a pointer to the subclass procedure. SetWindowLong returns a pointer to the original window procedure; use this pointer to pass messages to the original procedure. The subclass window procedure must use the CallWindowProc function to call the original window procedure.

The following example shows how to subclass an instance of an edit control in a dialog box. The subclass window procedure enables the edit control to receive all keyboard input, including the ENTER and TAB keys, whenever the control has the input focus.

WNDPROC wpOrigEditProc;

LRESULT APIENTRY EditBoxProc(

HWND hwndDlg,

UINT uMsg,

WPARAM wParam,

LPARAM lParam)

{

HWND hwndEdit;

switch(uMsg)

{

case WM_INITDIALOG:

// Retrieve the handle of the edit control.

hwndEdit = GetDlgItem(hwndDlg, ID_EDIT);

// Subclass the edit control.

wpOrigEditProc = (WNDPROC) SetWindowLong(hwndEdit,

GWL_WNDPROC, (LONG) EditSubclassProc);

//

// Continue the initialization procedure.

//

return TRUE;

case WM_DESTROY:

// Remove the subclass from the edit control.

SetWindowLong(hwndEdit, GWL_WNDPROC,

(LONG) wpOrigEditProc);

//

// Continue the cleanup procedure.

//

break;

}

return FALSE;

UNREFERENCED_PARAMETER(lParam);

}

// Subclass procedure

LRESULT APIENTRY EditSubclassProc(

HWND hwnd,

UINT uMsg,

WPARAM wParam,

LPARAM lParam)

{

if (uMsg == WM_GETDLGCODE)

return DLGC_WANTALLKEYS;

return CallWindowProc(wpOrigEditProc, hwnd, uMsg,

wParam, lParam);

}