MFC中獲得各個類的指針/句柄的總結(轉)

一般我們使用的框架是VC提供的Wizard生成的MFC App Wizard(exe)框架,無論是多文檔還是單文檔,都存在指針獲取和操作問題。

下 面這節內容主要是一般的框架,然後再講多線程中的指針使用。使用到的類需要包含響應的頭文件。首先一般獲得本類(視,文檔,對話框都支持)實例指針 this,用this的目的,主要可以通過類中的函數向其他類或者函數中髮指針,以便於在非本類中操作和使用本類中的功能。 這其中的關鍵在於理解 m_pMainWnd, AfxGetApp(),AfxGetMainWnd() 的意義!

1) 在View中獲得Doc指針

CYouSDIDoc *pDoc=GetDocument();一個視只能有一個文檔。

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) 獲得當前文檔指針

CDocument * pCurrentDoc =(CFrameWnd *)m_pMainWnd->GetActiveDocument();

6) 獲得狀態欄與工具欄指針

CStatusBar * pStatusBar=(CStatusBar *)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_STATUS_BAR);

CToolBar * pToolBar=(CtoolBar *)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_TOOLBAR);

7) 如果框架中加入工具欄和狀態欄變量還可以這樣

(CMainFrame *)GetParent()->m_wndToolBar;

(CMainFrame *)GetParent()->m_wndStatusBar;

8) 在Mainframe獲得菜單指針

CMenu *pMenu=m_pMainWnd->GetMenu();

9) 在任何類中獲得應用程序類

AfxGetInstanceHandle 得到句柄,AfxGetApp 得到指針

B1.如何在自己的類和“應用程序類”中獲得“文檔類”的句柄?

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(),調用 GetFirstViewPosition 和 GetNextView 函數得到指針。

C2.如何在自己的類和“應用程序類”中獲得“視圖類”句柄?

SDI GetActiveView 得到指針

MDI MDIGetActive() -> GetActiveView() 從 CMainFrame 得到指針,GetActiveView 從 CChildFrame 得到指針

 

最後提醒大家,在提取到各個句柄之後,因爲初次提取的都是標準類句柄,所以,在使用時要注意將標準句柄轉換成自己的類的句柄。

如:

AfxGetApp();//得到的是WinApp類的句柄,

所以操作前記得轉換成自己定義的類的句柄。

如:

((CMyApp*)AfxGetApp())->XXXX();//這的xxxx()就是你定義的類中間的成員。

 

MFC全局函數:

AfxFreeLibrary:釋放動態鏈接庫 

AfxGetApp:獲取當前CWinApp對象指針.

AfxGetAppName:獲取應用程序名 

AfxGetInstanceHandle:獲取當前應用程序句柄 

AfxGetMainWnd:獲取應用程序主窗口指針 

AfxGetResourceHandle:獲取資源句柄

AfxInitRichEdit:初始換1.0版本的rich edit控件 

AfxInitRichEdit2:初始換2.0版本的rich edit控件

AfxLoadLibrary:加載動態鏈接庫 

AfxRegisterWndClass:註冊窗口類 

AfxSocketInit:初始化Windows Socket 

AfxSetResourceHandle:設置資源句柄

AfxRegisterClass:註冊一個窗口類 

AfxBeginThread:創建新線程

AfxEndThread:終止線程 

AfxGetThread:獲取當前CWinThread對象指針.

AfxWinInit:WinMain函數主調,初始化CWinApp 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章