The CWindow class is primarily an encapsulation of a window handle and the Win32 APIs that manipulate a window. CWindow maintains the handle in the m_hWnd public data member. You can pass in an HWND to the constructor, use the Attach method, or use operator = to assign the window handle. By default, CWindow is constructed with a NULL handle. CWindow also provides a Create function, which thinly wraps the CreateWindowEx API. If Create is successful, the m_hWnd data member is set to the resulting window handle. Most CWindow functions are simple Win32 wrappers, but CWindow also provides some more complex methods, such as those that follow:
Temporary CWindow objects are often used to wrap an HWND for the duration of a function call. The following code section constructs a CWindow from an existing HWND and retrieves the BSTR version of the window text before returning:
BOOL GetDlgItemText(int nID, BSTR& bstrText) const { ATLASSERT(::IsWindow(m_hWnd)); HWND hWndCtl = GetDlgItem(nID); if(hWndCtl == NULL) return FALSE; return CWindow(hWndCtl).GetWindowText(bstrText); } |
Because CWindow implements the HWND operator, a CWindow object can be used anywhere an HWND is used.