cwnd, cdc, hwnd, and hdc | Beyond C++

by stilling2006 on 2010-06-21 18:24:29

For friends who are studying VC, these things should be quite familiar, right? But I still feel a bit confused, so I searched around on Baidu and recorded the following.

1. Objects and Handles

`CWnd` is a class, `HWnd` is a handle, and `CWnd` encapsulates `HWnd`.

```cpp

AfxGetMainWnd()->m_hwnd;

```

Similarly, the relationship between `CDC` and `HDC` is the same:

```cpp

CDC *pDC = new CDC;

HDC hdc;

pDC->GetSafeHdc(); // Obtain the handle via the object:

pDC->Attach(hdc); // Obtain the object via the handle:

```

`HWND` is a type defined in the SDK. It is an arbitrary 32-bit value used to represent a window when calling APIs.

`CWnd*` is a meaningful pointer that points to an instance of the MFC window class `CWnd`. Since MFC encapsulates the SDK, most calls can use `CWnd*` as a parameter, which can easily cause confusion. To get the handle from a `CWnd*`, you can use `pWnd->GetSafeHwnd()`. This method is safer than `pWnd->m_hWnd`, because the former returns `NULL` if `pWnd == NULL`, whereas the latter would result in an access violation.