首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

VC++ 類別間相互取得指標總結:App、Frame、View、Document、Menu、Toolbar、StatusBar

     編輯:VC 教學

核心取得路徑速查表

目標SDI 應用MDI 應用備註
CWinApp*AfxGetApp()全域唯一
HINSTANCEAfxGetInstanceHandle()模組句柄
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)通用取得方式

Document 反向取得 View

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(); // 編譯錯誤

常見使用場景

  • **View 中存取 Document 資料**:GetDocument()->m_data;
  • **Document 通知所有 View 更新**:遍歷 GetFirst/NextViewPosition → pView->UpdateUI();
  • **工具列/狀態列動態更新**:取得 MainFrame → 取得控制項 → 設定按鈕/文字;
  • **跨模組 (DLL/EXE) 存取主應用**:共用 AfxGetApp() 需同一模組,跨模組需傳遞指標或用訊息。

避坑指南

  • AfxGetMainWnd() 在非主執行緒可能返回 NULL,UI 操作務必在主執行緒;
  • MDI 下 MDIGetActive() 可能返回 NULL (無子視窗時);
  • GetDescendantWindow 依賴控制項 ID (AFX_IDW_TOOLBAR 等),自訂 ID 需一致;
  • 不要緩存這些指標跨訊息迴圈使用,視窗可能已銷毀重建。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved