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