CWnd::SubclassWindow

Call this member function to "dynamically subclass" a window and attach it to this CWnd object.

BOOL SubclassWindow(
   HWND hWnd 
);

Parameters

  • hWnd
    A handle to the window.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

When a window is dynamically subclassed, windows messages will route through the CWnd's message map and call message handlers in the CWnd's class first. Messages that are passed to the base class will be passed to the default message handler in the window.

This member function attaches the Windows control to a CWnd object and replaces the window's WndProc and AfxWndProc functions. The function stores a pointer to the old WndProc in the CWnd object.

Note

The window must not already be attached to an MFC object when this function is called.

Example

// The following code shows how to subclass the edit control and list box
// controls inside a combo box. It uses WM_CTLCOLOR for subclassing.
// CSuperComboBox represents the combo box
HBRUSH CSuperComboBox::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
   if (nCtlColor == CTLCOLOR_EDIT)
   {
      //Edit control
      if (m_edit.GetSafeHwnd() == NULL)
         m_edit.SubclassWindow(pWnd->GetSafeHwnd());
   }
   else if (nCtlColor == CTLCOLOR_LISTBOX)
   {
      //ListBox control
      if (m_listbox.GetSafeHwnd() == NULL)
         m_listbox.SubclassWindow(pWnd->GetSafeHwnd());
   }

   HBRUSH hbr = CComboBox::OnCtlColor(pDC, pWnd, nCtlColor);
   return hbr;
}

void CSuperComboBox::OnDestroy()
{
   //unsubclass edit and list box before destruction
   if (m_edit.GetSafeHwnd() != NULL)
      m_edit.UnsubclassWindow();
   if (m_listbox.GetSafeHwnd() != NULL)
      m_listbox.UnsubclassWindow();
   CComboBox::OnDestroy();
}

Requirements

Header: afxwin.h

See Also

Reference

CWnd Class

Hierarchy Chart

CWnd::DefWindowProc

CWnd::SubclassDlgItem

CWnd::Attach

CWnd::PreSubclassWindow

CWnd::UnsubclassWindow

Concepts

CWnd Members