Learning Hub Search Ctrl K

MFC › 2. Application Architecture

CWnd, Child Windows and Subclassing

Creating and customizing windows and controls.

intermediate #mfc#cwnd#subclassing#precreatewindow#oncreate#custom-control#createex

Explanation

CWnd wraps an HWND and is the base of frames, views, dialogs and every control. Two separate lifetimes matter: the C++ object and the window.

Creating a window:

  1. Construct the object.
  2. Call Create(...) / CreateEx(...), which calls PreCreateWindow(CREATESTRUCT&) (your chance to change styles, size and class name) and then sends WM_CREATE → OnCreate.
  3. When destroyed, the window gets WM_DESTROY then WM_NCDESTROY → PostNcDestroy, where self-deleting windows call delete this.

Useful overrides and handlers: OnCreate, OnSize, OnPaint/OnDraw, OnDestroy, PreTranslateMessage (see messages before dispatch, e.g. for accelerators), PreSubclassWindow.

Subclassing turns a standard control into your own class by routing its messages through your message map first:

  • Dialog controls: DDX_Control(pDX, IDC_NAME, m_myEdit) or m_myEdit.SubclassDlgItem(IDC_NAME, this) (in OnInitDialog).
  • A window you create: derive from CButton, CEdit… and call Create.

Example

A numeric-only edit box used as a drop-in replacement for CEdit:

#include <afxwin.h>
#include <afxcmn.h>

class CNumberEdit : public CEdit {
public:
    int GetValue() {                             // convenience accessor
        CString s;
        GetWindowText(s);
        return _ttoi(s);
    }
protected:

    afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) {
        if (_istdigit(static_cast<TCHAR>(nChar)) || nChar == VK_BACK)   // allow digits and Backspace
            CEdit::OnChar(nChar, nRepCnt, nFlags);                       // pass on to the base class
        else
            MessageBeep(MB_ICONEXCLAMATION);                             // swallow other characters
    }
    afx_msg int OnCreate(LPCREATESTRUCT lpcs) {
        if (CEdit::OnCreate(lpcs) == -1) return -1;                      // -1 = abort creation
        return 0;
    }
    DECLARE_MESSAGE_MAP()
};

BEGIN_MESSAGE_MAP(CNumberEdit, CEdit)
    ON_WM_CHAR()
    ON_WM_CREATE()
END_MESSAGE_MAP()

class CSettingsDlg : public CDialog {
public:
    enum { IDD = IDD_SETTINGS };
    explicit CSettingsDlg(CWnd* pParent = nullptr) : CDialog(IDD, pParent), m_port(0) {}
    int m_port;
protected:
    CNumberEdit m_portEdit;                      // control member subclasses IDC_PORT
    void DoDataExchange(CDataExchange* pDX) override {
        CDialog::DoDataExchange(pDX);
        DDX_Control(pDX, IDC_PORT, m_portEdit);  // subclass the dialog control
    }
    void OnOK() override {
        m_port = m_portEdit.GetValue();
        CDialog::OnOK();
    }
};

// A top-level window created without a resource: override PreCreateWindow
class CToolFrame : public CFrameWnd {
protected:
    BOOL PreCreateWindow(CREATESTRUCT& cs) override {
        if (!CFrameWnd::PreCreateWindow(cs)) return FALSE;
        cs.style &= ~FWS_ADDTOTITLE;             // no document name in the title
        cs.cx = 400; cs.cy = 300;                // initial size
        return TRUE;
    }
};

Common pitfalls

  • Calling window functions (GetWindowText, SetWindowPos) before the window exists (m_hWnd == nullptr) asserts in debug builds. Do it after Create / in OnInitDialog.
  • Always call the base-class handler (CEdit::OnChar) unless you really mean to swallow the message.
  • OnCreate must return -1 if the base OnCreate failed.
  • Deleting a CWnd object doesn’t destroy the window if it was attached with Attach (and vice versa): use DestroyWindow for the window and delete for heap-allocated objects.
  • CWnd::FromHandle and GetDlgItem return temporary objects; don’t keep them across message-loop iterations. Use control member variables instead.
  • Subclassing the same control twice asserts.

Win32 vs MFC

Raw Win32 subclassing uses SetWindowLongPtr(hwnd, GWLP_WNDPROC, newProc) and a hand-written forwarding procedure. MFC does the same through its message-map chain. Related: Message Maps, Common Controls.

Exercises

1. Where would you set the initial size of a frame window you create in code?

In PreCreateWindow, by changing cs.cx / cs.cy before the window is created.