4: Repainting the Window

Win32++

Tutorials

Menu of tutorials

Tutorial 1:   The Simplest WindowTutorial 2:   Using Classes and Inheritance
Tutorial 3:   Using Messages to Create a Scribble Window
Tutorial 4:   Repainting the Window
Tutorial 5:   Wrapping a Frame around our Scribble Window
Tutorial 6:   Customising Window Creation
Tutorial 7:   Customising the ToolBar
Tutorial 8:   Loading and Saving Files
Tutorial 9:   Printing
Tutorial 10: Finishing Touches

Tutorial 4:  Repainting the Window

The previous example fails to repaint the window. Repainting the window is required whenever the window is resized, restored from minimized, or when part of the window is revealed after being covered by another window.

The Windows API handles repainting automatically. When part of a window needs repainting, windows sends a WM_PAINT message to the application. Typically you would respond to this message with the code to redraw the entire client area of the window. You don't need to concern yourself with which parts of the client area need to be redrawn, as windows handles this part for you automatically.

Win32++ already contains the code to handle the WM_PAINT message in CWnd::WndProc. All we need to do is write the OnDraw function.  For our application here, we can store the various points in a vector, and have the OnDraw function draw the lines again.  The function to store the points looks like this.

void CView::StorePoint(int x, int y, bool PenDown)
{
  PlotPoint P1;
  P1.x = x;
  P1.y = y;
  P1.PenDown = PenDown;

  m_points.push_back(P1); //Add the point to the vector
}

Our OnDraw function looks like this.

void CView::OnDraw(CDC* pDC)
{
  if (m_points.size() > 0)
  {
    bool bDraw = false;  //Start with the pen up

    for (unsigned int i = 0 ; i < m_points.size(); i++)
    {
      if (bDraw) 
        pDC->LineTo(m_points[i].x, m_points[i].y);
      else 
        pDC->MoveTo(m_points[i].x, m_points[i].y);
      
      bDraw = m_points[i].PenDown;
    }
  }
}

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.