AfxGetApp() // 返回 CWinApp* 指針
AfxGetInstanceHandle() // 返回 HINSTANCE
SDI (單文檔界面):
CFrameWnd* pFrame = (CFrameWnd*)AfxGetMainWnd();
CView* pView = pFrame->GetActiveView();
CDocument* pDoc = pView->GetDocument();
MDI (多文檔界面):
CMDIFrameWnd* pMainFrame = (CMDIFrameWnd*)AfxGetMainWnd();
CMDIChildWnd* pChild = pMainFrame->MDIGetActive();
CView* pView = pChild->GetActiveView();
CDocument* pDoc = pView->GetDocument();
POSITION pos = pDoc->GetFirstViewPosition();
while (pos) {
CView* pView = pDoc->GetNextView(pos);
// 使用 pView...
}
CMenu* pMenu = AfxGetApp()->m_pMainWnd->GetMenu();
方法 A(視圖類中):
CMainFrame* pFrame = (CMainFrame*)GetParent();
CToolBar& toolbar = pFrame->m_wndToolBar;
CStatusBar& statusBar = pFrame->m_wndStatusBar;
方法 B(通用,通過主窗口查找子窗口):
CStatusBar* pStatusBar = (CStatusBar*)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_STATUS_BAR);
CToolBar* pToolBar = (CToolBar*)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_TOOLBAR);
上述 API 返回的均為基類指針(CWinApp*、CFrameWnd*、CView* 等),使用自定義派生類成員時必須強制轉換:
// 正確用法
((CMyApp*)AfxGetApp())->MyCustomFunction();
((CMainFrame*)AfxGetMainWnd())->m_wndToolBar.SetButtonInfo(...);
注意: MDI 下 AfxGetMainWnd() 返回 CMDIFrameWnd*,SDI 下返回 CFrameWnd*,轉換時需匹配實際框架類型。