天天看點

通過HWND獲得CWnd指針/通過CWnd擷取HWND

較常用的下面兩個方法:(MFC實作機制是使用映射機制,兩個之間互相MAP)

HWND hWnd = GetSafeHwnd();

CWnd *pWnd = CWnd::FromHandle(hWnd);      

通過HWND獲得CWnd指針

//獲得目前視窗的句柄 
HWND hWnd = GetSafeHwnd(); 
//通過HWND獲得CWnd指針 
CWnd *pWnd = CWnd::FromHandle(hWnd); 
CString strText = _T(""); 
strText.Format("pWnd = 0x%X\nthis = 0x%X\n", pWnd, this); 
AfxMessageBox(strText);       

1、GetSafeHwnd方法:該函數獲得視窗對象的視窗句柄。

Returns the window handle for a window. Returns NULL if the CWnd is not attached to a window or if it is used with a NULL CWnd pointer。

這個函數用途很廣,很多函數的參數要求是HWND,這時就需要使用GetSafeHwnd函數了。如:

  HWND hwnd;  
  CWnd* pWnd;  
  pWnd=((CFrameWnd*)(AfxGetApp()->m_pMainWnd))->GetActiveView();  
  hwnd=pWnd->GetDlgItem(IDC_EDIT2)->GetSafeHwnd();  
  ::SetWindowText(hwnd,m_strResult);       

其它的一些情況:

AfxWinInit 被WinMain調用的一個函數,用做MFC GUI程式初始化的一部份

AfxBeginThread 開始一個新的執行線程

AfxEndThread 結束一個舊的執行線程

AfxMessageBox 類似Windows API 函數MessageBox

AfxGetApp 取得application object(CWinApp衍生對象)的指針

AfxGetMainWnd 取得程式主視窗的指針

AfxGetInstance 取得程式的instance handle