//獲得當前窗口的句柄 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
AfxRegisterClass 以自定的WNDCLASS 注冊窗口類別
2、FromHandle方法:FromHandle(HANDLE h) 先查找由用戶定義的內核對象對象的封裝類, 如果找到直接返回,沒有找到構造一個臨時對象返回.