MFC版的Hello World
使用MFC類庫寫個Hello樣本程式比直接用Win32 API寫要簡單的多了。因為MFC用幾個類封裝了應用程式的建立,訊息迴圈等等東東。
閑話少說,先給來一個最簡單的MFC版Hello World.
//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!", "資訊", MB_ICONASTERISK);return FALSE;}
這個是最簡單的,它只用到了應用程式類(CWinApp),至於說它是怎麼做到的?你去看一下CWinApp類的實現,我在這裡只能簡單的告訴你,應用程式類(CWinApp)實現了WinMain()函數的調用,訊息迴圈等等。
下面再來個稍微複雜點的Hello World,這次不用系統的訊息框實現。這次加入了一個架構視窗類別(CFrameWnd),並且在其內部建立了一個CStatic控制項,用於顯示"Hello World"字串。
//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; }
不知道你們注意到了沒有?這一版的程式比上一版的訊息對話方塊程式的InitInstance()函數中的傳回值一個是True,一個是False。其實這一點區別,差異是很大的。有什麼區別大家看一下AfxWinMain()函數的實現就明白了。對了,AfxWinMain()函數在VC安裝目錄下的WinMain.CPP檔案中實現。