MFC中獲得各個(gè)類的指針/句柄的總結(jié)(轉(zhuǎn))
一般我們使用的框架是VC提供的Wizard生成的MFC App Wizard(exe)框架,無論是多文檔還是單文檔,都存在指針獲取和操作問題。
下 面這節(jié)內(nèi)容主要是一般的框架,然后再講多線程中的指針使用。使用到的類需要包含響應(yīng)的頭文件。首先一般獲得本類(視,文檔,對(duì)話框都支持)實(shí)例指針 this,用this的目的,主要可以通過類中的函數(shù)向其他類或者函數(shù)中發(fā)指針,以便于在非本類中操作和使用本類中的功能。 這其中的關(guān)鍵在于理解 m_pMainWnd, AfxGetApp(),AfxGetMainWnd() 的意義!
1) 在View中獲得Doc指針
CYouSDIDoc *pDoc=GetDocument();一個(gè)視只能有一個(gè)文檔。
2) 在App中獲得MainFrame指針
CWinApp 中的 m_pMainWnd變量就是MainFrame的指針,也可以: CMainFrame *pMain =(CMainFrame *)AfxGetMainWnd();
3) 在View中獲得MainFrame指針
CMainFrame *pMain=(CmaimFrame *)AfxGetApp()->m_pMainWnd;
4) 獲得View(已建立)指針
CMainFrame *pMain=(CmaimFrame *)AfxGetApp()->m_pMainWnd;
CyouView *pView=(CyouView *)pMain->GetActiveView();
5) 獲得當(dāng)前文檔指針
CDocument * pCurrentDoc =(CFrameWnd *)m_pMainWnd->GetActiveDocument();
6) 獲得狀態(tài)欄與工具欄指針
CStatusBar * pStatusBar=(CStatusBar *)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_STATUS_BAR);
CToolBar * pToolBar=(CtoolBar *)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_TOOLBAR);
7) 如果框架中加入工具欄和狀態(tài)欄變量還可以這樣
(CMainFrame *)GetParent()->m_wndToolBar;
(CMainFrame *)GetParent()->m_wndStatusBar;
8) 在Mainframe獲得菜單指針
CMenu *pMenu=m_pMainWnd->GetMenu();
9) 在任何類中獲得應(yīng)用程序類
AfxGetInstanceHandle 得到句柄,AfxGetApp 得到指針
B1.如何在自己的類和“應(yīng)用程序類”中獲得“文檔類”的句柄?
SDI AfxGetMainWnd() -> GetActiveView() -> GetDocument() 得到指針
MDI AfxGetMainWnd() -> MDIGetActive() -> GetActiveView() -> GetDocument() 得到指針
B3.如何在“框架類”中獲得“文檔類”句柄?
SDI GetActiveView() -> GetDocument() 得到指針,MDI MDIGetActive() -> GetActiveView() -> GetDocument() 從 CMainFrame 得到指針,GetActiveView() -> GetDocument() 從 CChildFrame 得到指針
B4.如何在“視圖類”中獲得“文檔類”句柄?
GetDocument()
C1.如何在“文檔類”中獲得“視圖類”句柄?
GetView(),調(diào)用 GetFirstViewPosition 和 GetNextView 函數(shù)得到指針。
C2.如何在自己的類和“應(yīng)用程序類”中獲得“視圖類”句柄?
SDI GetActiveView 得到指針
MDI MDIGetActive() -> GetActiveView() 從 CMainFrame 得到指針,GetActiveView 從 CChildFrame 得到指針
?
最后提醒大家,在提取到各個(gè)句柄之后,因?yàn)槌醮翁崛〉亩际菢?biāo)準(zhǔn)類句柄,所以,在使用時(shí)要注意將標(biāo)準(zhǔn)句柄轉(zhuǎn)換成自己的類的句柄。
如:
AfxGetApp();//得到的是WinApp類的句柄,
所以操作前記得轉(zhuǎn)換成自己定義的類的句柄。
如:
((CMyApp*)AfxGetApp())->XXXX();//這的xxxx()就是你定義的類中間的成員。
?
MFC全局函數(shù):
AfxFreeLibrary:釋放動(dòng)態(tài)鏈接庫(kù)?
AfxGetApp:獲取當(dāng)前CWinApp對(duì)象指針.
AfxGetAppName:獲取應(yīng)用程序名?
AfxGetInstanceHandle:獲取當(dāng)前應(yīng)用程序句柄?
AfxGetMainWnd:獲取應(yīng)用程序主窗口指針?
AfxGetResourceHandle:獲取資源句柄
AfxInitRichEdit:初始換1.0版本的rich edit控件?
AfxInitRichEdit2:初始換2.0版本的rich edit控件
AfxLoadLibrary:加載動(dòng)態(tài)鏈接庫(kù)?
AfxRegisterWndClass:注冊(cè)窗口類?
AfxSocketInit:初始化Windows Socket?
AfxSetResourceHandle:設(shè)置資源句柄
AfxRegisterClass:注冊(cè)一個(gè)窗口類?
AfxBeginThread:創(chuàng)建新線程
AfxEndThread:終止線程?
AfxGetThread:獲取當(dāng)前CWinThread對(duì)象指針.
AfxWinInit:WinMain函數(shù)主調(diào),初始化CWinApp?