| 優勢 | 書本描述 | 雷神實戰體會 |
|---|---|---|
| 標準化結構 | 應用程式採用標準化結構 | 團隊協作時,新成員一天即可上手專案架構 |
| 程式碼精簡、執行快 | 動態連結 MFC DLL,應用程式極小 | Release 版僅 100KB 左右,但依賴系統 MFC DLL (需部署合併模塊) |
| VC++ 工具降低編碼複雜度 | AppWizard/ClassWizard/Resource Editor 三位一體 | 比純 SDK 手寫 RegisterClass/CreateWindow 快 10 倍以上 |
| 類庫功能極豐富 | 涵蓋集合、資料庫、網絡、OLE、打印... | 避免重複造輪子;但也導致「只會用 Wizard 不懂底層」的假高手 |
真正的高手:內功深厚、基本功扎實、招式隨心所欲、無招勝有招。
Project → Settings → General → **Use MFC in a Static Library** (靜態鏈接,無需部署 DLL,適合學習)。
// 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
#include "MyApp.h"
CMyApp theApp; // 全局應用程式對象
BOOL CMyApp::InitInstance() {
m_pMainWnd = new CMyFrame();
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}
BEGIN_MESSAGE_MAP(CMyFrame, CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_PAINT()
END_MESSAGE_MAP()
CMyFrame::CMyFrame() {
Create(NULL, "MYAPP Application"); // 創建窗口
}
void CMyFrame::OnLButtonDown(UINT nFlags, CPoint point) {
TRACE("Entering CMyFrame::OnLButtonDown - %lx,%d,%d\n", nFlags, point.x, point.y);
}
void CMyFrame::OnPaint() {
CPaintDC dc(this);
dc.TextOut(0, 0, "Hello World!");
}
CWinApp 派生類 CMyApp 的全局對象 theApp 是程式入口點;MFC 隱藏的 WinMain 會尋找並調用它。InitInstance:重寫此虛函數完成主窗口構造、顯示、更新。CWinApp::Run (基類隱藏) 負責消息循環 (相當於 SDK 的 GetMessage/DispatchMessage)。CFrameWnd 派生類 CMyFrame 代表主窗口;構造函數調用 Create 完成窗口創建。BEGIN_MESSAGE_MAP / ON_WM_* / END_MESSAGE_MAP 將 WM_LBUTTONDOWN、WM_PAINT 映射到成員函數。OnPaint 中使用 CPaintDC (自動 BeginPaint/EndPaint) 繪製文字;若放在 OnLButtonDown 則最小化恢復後文字消失 (因無 WM_PAINT 重繪)。WM_CLOSE → DestroyWindow → WM_DESTROY → PostQuitMessage → 退出 Run → 刪除 theApp。CMyApp01View → OnDraw → 添加一行:pDC->TextOut(10, 10, "雷神願意和所有學VC的朋友共同進步!");**文檔 (Document)** ≈ 後台數據模型 (數據庫、內存數據結構)。
**視圖 (View)** ≈ 前台展示界面 (繪圖、編輯、打印)。
**同一文檔可對應多視圖** (如同一數據同時以表格、圖表、報表顯示);文檔變更自動通知所有視圖更新。這是 MFC 核心設計模式,也是「關注點分離」在 Windows 桌面開發的經典實踐。
Day 3:消息映射機制深度解析、視圖類 CView 核心虛函數、OnDraw 繪圖實戰、Source Browser 看類全貌。