| 目標 | SDI 應用 | MDI 應用 | 備註 |
|---|---|---|---|
CWinApp* | AfxGetApp() | 全域唯一 | |
HINSTANCE | AfxGetInstanceHandle() | 模組句柄 | |
CMainFrame* | (CMainFrame*)AfxGetMainWnd() | 主框架視窗 | |
CView* (作用中) | AfxGetMainWnd()->GetActiveView() | AfxGetMainWnd()->MDIGetActive()->GetActiveView() | MDI 需先取得作用中子框架 |
CDocument* | GetActiveView()->GetDocument() | MDIGetActive()->GetActiveView()->GetDocument() | 經由 View 取得 |
CMenu* | AfxGetApp()->m_pMainWnd->GetMenu() | 主選單 | |
| Toolbar | (CToolBar*)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_TOOLBAR) | 通用取得方式 | |
| StatusBar | (CStatusBar*)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_STATUS_BAR) | 通用取得方式 | |
POSITION pos = pDoc->GetFirstViewPosition();
while (pos) {
CView* pView = pDoc->GetNextView(pos);
// 針對特定 View 類型 dynamic_cast
}
所有上述 API 回傳基類指標 (CWnd*, CView*, CDocument*),**使用前必須強制轉型**為實際衍生類:
// 正確
((CMyApp*)AfxGetApp())->MyCustomFunction();
((CMainFrame*)AfxGetMainWnd())->m_wndToolBar.SetButtonInfo(...);
((CMyView*)pView)->RefreshData();
// 錯誤:基類指標無法直接呼叫衍生類成員
AfxGetApp()->MyCustomFunction(); // 編譯錯誤
GetDocument()->m_data;GetFirst/NextViewPosition → pView->UpdateUI();AfxGetApp() 需同一模組,跨模組需傳遞指標或用訊息。AfxGetMainWnd() 在非主執行緒可能返回 NULL,UI 操作務必在主執行緒;MDIGetActive() 可能返回 NULL (無子視窗時);GetDescendantWindow 依賴控制項 ID (AFX_IDW_TOOLBAR 等),自訂 ID 需一致;