6.6 Add Message Handlers for Creation and Sizing

This section explains the eighth step in writing Phone Book: add message-handler functions to the CMainWindow class for the WM_SIZE, and WM_CREATE messages, and add the OnClose member function.

·To add these message-handler functions:

1.Add the following WM_CREATE message-handler function to the CMainWindow section of your VIEW.CPP file below your OnAbout member function and above the OnClose member function that you added earlier. This will preserve the same order as in Listing 2 in Chapter 5.

// CMainWindow::OnCreate

// Queries the current text metrics to determine char size.

//

int CMainWindow::OnCreate( LPCREATESTRUCT )

{

TEXTMETRIC tm;

// Get the text metrics.

CDC* dc = GetDC();

dc -> GetTextMetrics( &tm );

ReleaseDC( dc );

// Decide the statistics on how many rows, etc., we can display.

m_cxChar = tm.tmAveCharWidth;

m_cxCaps = ( (tm.tmPitchAndFamily & 1 )? 3 : 2 ) * m_cxChar / 2;

m_cyChar = tm.tmHeight + tm.tmExternalLeading;

m_nMaxWidth = ( SIZENAME + SIZEPHONE + 1 ) * m_cxCaps;

m_nVscrollPos = m_nHscrollPos = 0;

return 0;

}

OnCreate gets and stores text metric and scroll information to be used later in the program. It's called when Windows sends a WM_CREATE message when the window is created.

2.Add the following WM_SIZE message-handler function to the CMainWindow section of your VIEW.CPP file below OnCreate and above OnClose:

// CMainWindow::OnSize

// When resized, we need to recalculate our scrollbar ranges based on

// what part of the database is visible.

//

void CMainWindow::OnSize( UINT, int x, int y )

{

m_cxClient = x;

m_cyClient = y;

m_nVscrollMax = max( 0,

(int)( m_people.GetCount() ) - m_cyClient / m_cyChar );

m_nVscrollPos = min( m_nVscrollPos, m_nVscrollMax );

SetScrollRange( SB_VERT, 0, m_nVscrollMax, FALSE );

SetScrollPos( SB_VERT, m_nVscrollPos, TRUE );

m_nHscrollMax = max( 0, ( m_nMaxWidth - m_cxClient ) / m_cxChar );

m_nHscrollPos = min( m_nHscrollPos, m_nHscrollMax );

SetScrollRange( SB_HORZ, 0, m_nHscrollMax, FALSE );

SetScrollPos( SB_HORZ, m_nHscrollPos, TRUE );

Invalidate( TRUE );

}

OnSize recalculates the size of the window's client area, resets the scrollbars, and invalidates the client area to cause repainting.

To continue the tutorial, see “Add Scrolling Member Functions” on page 227. For more information on the handlers you just added, see the discussion in the next section.