使用Visual Studio新建一个空项目,项目命名为HelloMFC,完成后,打开项目属性页面,将配置属性选项卡中的常规项打开,将其中的MFC的使用属性栏改为:在静态库中使用MFC或者在共享DLL中使用MFC,同时将字符集属性栏改为使用Unicode字符集。
图1-1 新建一个空项目
图1-2 更改项目属性
完成以上更改后,在项目头文件中添加新建项头文件,命名为Hello.h,头文件代码如下:
1 class CMyApp : public CWinApp 2 { 3 public: 4 virtual BOOL InitInstance(); 5 }; 6 7 class CMainWindow : public CFrameWnd 8 { 9 public: 10 CMainWindow(); 11 protected: 12 afx_msg void OnPaint(); 13 DECLARE_MESSAGE_MAP() 14 };
同时在项目源文件中添加新建项C++文件,命名为Hello.cpp,源文件代码如下:
1 #include <afxwin.h> 2 #include "Hello.h" 3 4 CMyApp myApp; 5 6 BOOL CMyApp::InitInstance() 7 { 8 m_pMainWnd = new CMainWindow(); 9 m_pMainWnd->ShowWindow(m_nCmdShow); 10 m_pMainWnd->UpdateData(); 11 return TRUE; 12 } 13 14 BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd) 15 ON_WM_PAINT() 16 END_MESSAGE_MAP() 17 18 CMainWindow::CMainWindow() 19 { 20 Create(NULL, _T("The Hello Application")); 21 } 22 23 void CMainWindow::OnPaint() 24 { 25 CPaintDC dc(this); 26 27 CRect rect; 28 GetClientRect(&rect); 29 30 dc.DrawText(_T("Hello, MFC"), -1, &rect, 31 DT_SINGLELINE | DT_CENTER | DT_VCENTER); 32 }
最后运行程序,会在窗口中央画出“Hello MFC”字样。
图1-3 程序运行结果