要实现最简单MFC窗口,只需要两个类就可以,CMyApp继承CWinApp,CMainWindow继承CFrameWnd,实现两个类就可以得到一个简单的窗口。
下面的代码用于实现了一个简单的mfc窗口,还在CMainWindow中用消息映射方式实现绘画,包括椭圆绘制和文字的绘制,其中用到了CPaintDC类和CRect类,大家看具体代码将可以更好的理解其作用。
头文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#pragma once #include <afxwin.h> class CMyApp : public CWinApp { public: virtual BOOL InitInstance(); }; class CMainWindow : public CFrameWnd { public: CMainWindow(); protected: afx_msg void OnPaint(); DECLARE_MESSAGE_MAP(); }; |
源文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include "hello.h" CMyApp myApp; BOOL CMyApp::InitInstance() { this->m_pMainWnd = new CMainWindow(); this->m_pMainWnd->ShowWindow(this->m_nCmdShow); this->m_pMainWnd->UpdateWindow(); return TRUE; } BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd) ON_WM_PAINT() END_MESSAGE_MAP() CMainWindow::CMainWindow() { this->Create(NULL, TEXT("The Hello Application")); } void CMainWindow::OnPaint() { CPaintDC dc(this); dc.Ellipse(100, 100, 200, 300); CRect rect; this->GetClientRect(&rect); dc.DrawText(TEXT("Hello,MFC!"), -1, &rect, DT_SINGLELINE | DT_CENTER); } |