Replacing HWND and HDC Parameters

WindowProc is within the scope of the view class. That is, you can think of the function as being inside a CView-derived C++ window object. Also, WindowProc doesn't pass you an HWND the way your old WndProc did. This means that when you call Windows API functions directly, you should pass them the HWND belonging to the C++ window object, which is stored in the object's m_hWnd member variable. To do so, add a line of code like the following at the top of WindowProc:


HWND hWnd = GetSafeHwnd();

where hWnd is whatever name your code uses for the HWND parameter to Windows API functions. In effect, this globally replaces the old parameter throughout WindowProc with the correct value. GetSafeHwnd is a CWnd member function that returns a copy of the HWND stored in m_hWnd that is safe to use directly this way.

Note Calling GetSafeHwnd is a useful technique in the present context, but it's really not a common occurrence in most MFC code. It's used here to avoid manually replacing a lot of variable names.

If you're working with a member function that calls Windows API functions with an HDC parameter, you can do something similar. Add a line of code like the following at the top of your override:


HDC hDC = pDC->GetSafeHdc();

This code assumes you already have a pointer (pDC) to an MFC object of class CDC, which encapsulates a device context handle (HDC). If you don't have such a pointer, you can create a CDC-derived object as follows :


CClientDC dc(this); // a device context for the view (client area) HDC hDC = dc.GetSafeHdc();

The CClientDC constructor calls GetDC and the destructor calls ReleaseDC for you.

For SHOWDIB, add the HWND code shown above at the top of CShowDibView::WindowProc. You'll add the HDC code to another function override later.

Also, where SHOWDIB's WndProc has a parameter called iMessage, WindowProc's parameter is called message. To correct this difference, add the following line just before the switch statement:


UINT iMessage = message;

This is similar to the hWnd replacement code shown earlier.

Tip After cleaning up WindowProc (and after the next several steps in the process), you can compile the program. Parts of it won't work yet, but you can catch typographical errors.