MFC › 2. Application Architecture
CWnd, Child Windows and Subclassing
Creating and customizing windows and controls.
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:
- Construct the object.
- Call
Create(...)/CreateEx(...), which callsPreCreateWindow(CREATESTRUCT&)(your chance to change styles, size and class name) and then sendsWM_CREATE→OnCreate. - When destroyed, the window gets
WM_DESTROYthenWM_NCDESTROY→PostNcDestroy, where self-deleting windows calldelete 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)orm_myEdit.SubclassDlgItem(IDC_NAME, this)(inOnInitDialog). - A window you create: derive from
CButton,CEdit… and callCreate.
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 afterCreate/ inOnInitDialog. - Always call the base-class handler (
CEdit::OnChar) unless you really mean to swallow the message. OnCreatemust return-1if the baseOnCreatefailed.- Deleting a
CWndobject doesn’t destroy the window if it was attached withAttach(and vice versa): useDestroyWindowfor the window anddeletefor heap-allocated objects. CWnd::FromHandleandGetDlgItemreturn 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.