MFC版的Hello World

來源:互聯網
上載者:User

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檔案中實現。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.