Hello world for MFC
Using the MFC class library to write a hello sample program is much easier than using the Win32 API directly. Because MFC uses several classes to encapsulate application creation, message loops, and so on.
Let's talk less about it. First, let's get a simple version of Hello world for MFC.
//Hello.h#ifndef Hello1_H_#define Hello1_H_ #include <afxwin.h>// Declare the application classclass CTestApp : public CWinApp{public:virtual BOOL InitInstance();};// Create an instance of the application classCTestApp TestApp; #endif //Hello1_H_
// Hello. CPP # include "hello. H "// The initinstance function is called // once when the application first executesbool ctestapp: initinstance () {MessageBox (0," Hello world! "," Information ", mb_iconasterisk); Return false ;}
This is the simplest. It only applies to the application class (cwinapp). How does it work? Let's take a look at the implementation of the cwinapp class. Here I can only tell you that the application class (cwinapp) implements the winmain () function call and message loop.
Next we will introduce a slightly more complex Hello world, which is not implemented in the system message box this time. This time I added a framework window class (cframewnd) and created a cstatic control inside it to display the "Hello World" string.
//static1.h#ifndef static1_H_#define static1_H_ #include <afxwin.h>// Declare the application classclass CTestApp : public CWinApp{public:virtual BOOL InitInstance();};// Create an instance of the application classCTestApp TestApp; // Declare the main window classclass CTestWindow : public CFrameWnd{private:CStatic* cs;public:CTestWindow();~CTestWindow();};#endif //static1_H_
//static1.cpp#include "static1.h"// The InitInstance function is called// once when the application first executesBOOL CTestApp::InitInstance(){m_pMainWnd = new CTestWindow();m_pMainWnd->ShowWindow(m_nCmdShow);m_pMainWnd->UpdateWindow();return TRUE;}// The constructor for the window classCTestWindow::CTestWindow(){ CRect r;// Create the window itselfCreate(NULL, "CStatic Tests", WS_OVERLAPPEDWINDOW,CRect(0,0,100,100));// Get the size of the client rectangleGetClientRect(&r);r.InflateRect(-10,-10);// Create a static labelcs = new CStatic();cs->Create("hello world",WS_CHILD|WS_VISIBLE|WS_BORDER|SS_CENTER,r,this);}CTestWindow::~CTestWindow(){delete cs; }
Do you notice this? This version of the program returns true and false compared to the initinstance () function of the previous version of the message dialog box program. In fact, this difference is very large. Let's take a look at the implementation of the afxwinmain () function. By the way, the afxwinmain () function is implemented in the winmain. cpp file under the VC installation directory.