MFC版的Hello World

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 class
class CTestApp : public CWinApp
{
public:
	virtual BOOL InitInstance();
};

// Create an instance of the application class
CTestApp TestApp;  

#endif //Hello1_H_ 

//Hello.cpp

#include "Hello.h"


// The InitInstance function is called
// once when the application first executes
BOOL 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 class
class CTestApp : public CWinApp
{
public:
	virtual BOOL InitInstance();
};

// Create an instance of the application class
CTestApp TestApp;  

// Declare the main window class
class 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 executes
BOOL CTestApp::InitInstance()
{
	m_pMainWnd = new CTestWindow();
	m_pMainWnd->ShowWindow(m_nCmdShow);
	m_pMainWnd->UpdateWindow();
	return TRUE;
}

// The constructor for the window class
CTestWindow::CTestWindow()
{ 
	CRect r;

	// Create the window itself
	Create(NULL, 
		"CStatic Tests", 
		WS_OVERLAPPEDWINDOW,
		CRect(0,0,100,100));
	
	// Get the size of the client rectangle
	GetClientRect(&r);
	r.InflateRect(-10,-10);
	
	// Create a static label
	cs = 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文件中實現。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章