MemDC in OnPaint()-function

Andreas D. picture Andreas D. · Jul 12, 2012 · Viewed 7.5k times · Source

My OnPaint() function calls several other drawing functions.

 void CGraph::OnPaint ()
 {
    CPaintDC dc(this);
    // CMemDC DC(&dc);

    dc.SetViewportOrg (0, 400);
    dc.SetMapMode(MM_ISOTROPIC);
    dc.SetWindowExt(1000, 800);
    dc.SetViewportExt(1000, -800);

    ProcessData ();
    DrawCoordinateSystem (&dc);
    DrawGrid (&dc);
    DrawGraph (&dc);
}

Example of DrawCoordianteSystem:

void CGraph::DrawCoordinateSystem (CDC* pDC)
{
   CPen PenBlack (PS_SOLID, 1, RGB(0, 0, 0));
   pDC->SelectObject (PenBlack);
   // Rectangle round the system
   pDC->Rectangle (0, -400, 1000, 400);
   // Horizontal axis
   pDC->MoveTo (0, 0);
   pDC->LineTo (1000, 0);
   pDC->SetTextColor (RGB(0,0,0));
   pDC->SetBkColor (RGB(240, 240, 240));
   pDC->TextOut (1001, 0, L"0");
   // Vertical axis
   pDC->MoveTo (0, -400);
   pDC->LineTo (0, 400);
}

I now want to avoid flickering with CMemDC. However, i can't get it to work right. Can somebody show me how to implement CMemDC right?

Thanks

Answer

snowdude picture snowdude · Jul 12, 2012

You need to load the memory DC with a bitmap to then BitBlt to the screen DC.

Try something like:

CDC dcMem;
CBitmap bitmap;

dcMem.CreateCompatibleDC( pDC );
bitmap.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height())
CBitmap* pOldBitmap = dcMem.SelectObject(&bitmap);

... DO ALL YOUR DRAWING TO dcMem ...

pDC->BitBlt(rect.left, rect.top, rect.Width(), rect.Height(), &dcMem, 0, 0, SRCCOPY);

dcMem.SelectObject(pOldBitmap)