MFC › 1. Getting Started
Hello MFC: CWinApp and CFrameWnd
The smallest MFC application: one application object and one frame window.
beginner #mfc#cwinapp#cframewnd#initinstance
Explanation
Every MFC program has exactly one global object derived from CWinApp. MFC supplies WinMain; it constructs your global app object, then calls InitInstance() where you create the main window and start the message loop (Run()).
Project setup in Visual Studio: Empty C++ project → Properties → Advanced → Use of MFC: Use MFC in a Shared DLL, and set Subsystem to Windows.
Example
#include <afxwin.h>
class CMainFrame : public CFrameWnd {
public:
CMainFrame() { Create(nullptr, _T("Hello MFC")); }
};
class CHelloApp : public CWinApp {
public:
BOOL InitInstance() override {
m_pMainWnd = new CMainFrame(); // frame deletes itself in PostNcDestroy
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE; // TRUE = enter the message loop
}
};
CHelloApp theApp; // the one and only application object
Pitfalls
- Forgetting
#include <afxwin.h>or the right “Use of MFC” setting gives linker errors aboutWinMain/_tWinMain. - Returning
FALSEfromInitInstanceexits immediately. - Use
_T("...")/TCHARso the code builds as Unicode or ANSI. - Do not
deletethe main frame yourself;CFrameWndcleans itself up onWM_NCDESTROY.
Exercises
1. Which function creates the window, and which one runs the message loop?
InitInstance creates it; CWinApp::Run (called by MFC after InitInstance returns TRUE) pumps messages.