Working with GDI Coordinates

Notice that the addition of scrolling didn’t require you to modify the OnDraw member function of CScribbleView. If the drawing function is unchanged, why does the window display different portions of the document depending on where the user has scrolled to? Because the document is displayed using coordinates relative to an origin used by GDI. When this origin was fixed at the upper-left corner of the client area, the part of the document that was visible was always the same. By moving the origin used by GDI, CScrollView can adjust which portion of the document is shown in the client area of the window and which portions are hidden.

The origin used by GDI is a characteristic of a device context; it is used by the member functions of the CDC class. If you want to make adjustments to the CDC object used by your view, you can override the OnPrepareDC member function defined by CView. CScrollView overrides OnPrepareDC to move the device context’s origin to reflect the currently scrolled position. OnPrepareDC is always called by the framework before it calls OnDraw. As a result, you don’t have to make any changes to the OnDraw function to draw a properly scrolled document; all the work needed to do scrolling is done to the device context before OnDraw receives it.

Note that changing the device context’s origin doesn’t affect the coordinates you receive with Windows messages such as WM_LBUTTONDOWN or WM_MOUSEMOVE; the points accompanying those messages are still specified in coordinates relative to the upper-left corner of the client area. This is because Windows messages are not part of a device context, so they are unaffected by changes to the GDI origin. Thus, CScribbleView must now deal with two types of coordinates: