Scrolling the View
After adding all these controls, you might find that they don't all fit in the window.As Figure 10.10 shows, no scrollbars appear, even though CCommonView inherits from
CScrollView. You need to set the scroll sizes in order for scrolling to work properly.
FIG. 10.10 The view does not automatically gain scrollbars as more controls are added.
Expand CCommonView and double-click OnInitialUpdate() in ClassView. Edit it so that
it looks like this:
void CCommonView::OnInitialUpdate()
{
CScrollView::OnInitialUpdate();
CSize sizeTotal;
sizeTotal.cx = 700;
sizeTotal.cy = 500;
SetScrollSizes(MM_TEXT, sizeTotal);
}
The last control you added, the month calendar, ran from the coordinates (470, 260) to
(650, 420). This code states that the entire document is 700*500 pixels, so it leaves a nice
white margin between that last control and the edge of the view. When the displayed
window is less than 700*500, you get scrollbars. When it's larger, you don't. The call to
SetScrollSizes() takes care of all the work involved in making scrollbars, sizing them
to represent the proportion of the document that is displayed, and dealing with the
user's scrollbar clicks. Try it yourself - build Common one more time and experiment
with resizing it and scrolling around. (The scrollbars weren't there before because the
OnInitialUpdate() generated by AppWizard stated that the app was 100*100 pixels, which
wouldn't require scrollbars.)
So, what's going on? Vertical scrolling is fine, but horizontal scrolling blows up your
application, right? You can use the techniques described in Appendix D, "Debugging," to
find the cause. The problem is in OnHScroll(), which assumed that any horizontal
scrolling was related to the slider control and acted accordingly. Edit that function
so that it looks like this:
void CCommonView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar*
pScrollBar)
{
CSliderCtrl* slider = (CSliderCtrl*)pScrollBar;
if (slider == &m_trackbar)
{
int position = slider->GetPos();
char s[10];
wsprintf(s, "%d ", position);
CClientDC clientDC(this);
clientDC.TextOut(390, 22, s);
}
CScrollView::OnHScroll(nSBCode, nPos, pScrollBar);
}
Now the slider code is executed only when the scrollbar that was clicked is the one
kept in m_trackbar. The rest of the time, the work is simply delegated to the base class.
For the last time, build and test Common - everything should be perfect now.
No comments:
Post a Comment