This is an article that I wrote sometime ago to demonstrate that MFC programs can be written and compiled much like the famed “Hello World” console example. This program does pretty much nothing other than create a window. The objectives are:
- Demonstrate how simple it is to create a window using MFC classes without using the wizard
- Demonstrate that compiling and linking an MFC program is as simple as a regular console program
- Outline basic MFC concepts
#include <afxwin.h>
// declare a simple window
class MyWnd : public CWnd {
public:
MyWnd() : CWnd()
{}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(MyWnd, CWnd)
END_MESSAGE_MAP()
//
// There must be one instance of a CWinApp derived class per program
class MyApp : public CWinApp {
CWnd* m_pWnd;
public:
MyApp()
: CWinApp()
, m_pWnd(0)
{}
BOOL InitInstance()
{
MyWnd* pWnd = new MyWnd;
if (!pWnd->CreateEx(WS_EX_CLIENTEDGE,
::AfxRegisterWndClass(0, 0,
::GetSysColorBrush(COLOR_WINDOW), 0),
_T("My Window"),
WS_OVERLAPPEDWINDOW,
0,
0,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
0) )
return FALSE;
m_pWnd = m_pMainWnd = pWnd;
pWnd->ShowWindow(SW_SHOW);
pWnd->UpdateWindow();
return TRUE;
}
int ExitInstance()
{
delete m_pWnd; m_pWnd = 0;
return 0;
}
};
MyApp theApp;
Compile this using the following command line in Visual Studio 2005 Command Prompt:
cl /MT /EHsc /D "_UNICODE" /D "UNICODE" tut1.cpp /link /subsystem:windows
/ENTRY:"wWinMainCRTStartup"
MyWnd derives from CWnd which is the base MFC class that represents a window. All windowing classes are derived from CWnd including the standard Win32 controls such as Button, Listbox, etc. Right after its constructor, MyWnd declares a message map using the DECLARE_MESSAGE_MAP() macro. This macro expands to insert the necessary data members in the class declaration that would allow us to specify the class methods to be invoked for handling the various messages that are sent to the window. Specifying the individual method to be invoked in response to a windows message will be covered in the next tutorial.
Every MFC program requires a single instance of a CWinApp derived class. This forms the entry point into the program upon its startup. InitInstance() is this entry point and ExitInstance() being the exit point that is invoked when the user quits the program. This would be a good place to program specific initialization/de-initialization code.
Inside InitInstance(), we create the window by instantiating MyWnd object and calling the CWnd::CreateEx() method. The second parameter to CreateEx() is the return value from the call
::AfxRegisterWndClass(0, 0, ::GetSysColorBrush(COLOR_WINDOW), 0);
which essentialy returns an ATOM (a Win32 type) which specifies the default properties for a window (such as default style, cursor, background color, etc). Refer to the documentation of Win32 API RegisterClass() for more on window classes.