MyApp01。CMyApp01View 類別,雙擊 OnDraw 函數。// TODO: add draw code for native data here 處加入:void CMyApp01View::OnDraw(CDC* pDC)
{
CMyApp01Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
pDC->TextOut(10, 10, _T("雷神願意和所有學 VC 的朋友共同進步!"));
// TODO: add draw code for native data here
}
編譯執行(F5),視窗左上角顯示文字,具備選單、工具列、狀態列、關於對話框、列印預覽等完整 Windows 應用程式特性。
建立 Win32 Application 專案,手動加入 MyApp.h、MyApp.cpp:
// MyApp.h
class CMyApp : public CWinApp
{
public:
virtual BOOL InitInstance();
};
class CMyFrame : public CFrameWnd
{
public:
CMyFrame();
protected:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
};
// MyApp.cpp
#include "MyApp.h"
CMyApp theApp; // 全域應用程式物件
BOOL CMyApp::InitInstance()
{
m_pMainWnd = new CMyFrame;
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}
CMyFrame::CMyFrame()
{
Create(NULL, _T("手工建立的 MFC 視窗"));
}
BEGIN_MESSAGE_MAP(CMyFrame, CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_PAINT()
END_MESSAGE_MAP()
void CMyFrame::OnLButtonDown(UINT nFlags, CPoint point)
{
CClientDC dc(this);
dc.TextOut(point.x, point.y, _T("滑鼠左鍵點擊處"));
}
void CMyFrame::OnPaint()
{
CPaintDC dc(this);
dc.TextOut(10, 10, _T("WM_PAINT 重繪"));
}
| 類別 | 角色 | 關鍵方法 |
|---|---|---|
CWinApp | 應用程式物件,單一實例 | InitInstance, Run |
CFrameWnd | 主視窗框架 | Create, LoadFrame |
CView | 視圖類別,繪製資料 | OnDraw, OnInitialUpdate |
CDocument | 文件類別,管理資料 | Serialize, SetModifiedFlag |
TextOut 字串改為自訂內容,觀察重繪行為。\VC98\MFC\SRC,追蹤 CWinApp::Run、CView::OnDraw 呼叫鏈。MFC 雖屬經典架構,但其文件/視圖分離、訊息映射、動態建立等設計模式仍具現代參考價值,奠定 Windows 程式設計核心功力。