mfcvisual-c++-2005

How to get the "screen image" to a CImage to save it?


How to get from CPaintDC image(screen) to Cimage?

CPaintDC dc(this);

dc.FillSolidRect( 20-1, 200+1, 200*3, 400+2, (COLORREF) 0x0 );

dc.SelectObject(pen1);

dc.MoveTo(20,400);
for(int i = 0;i<200;i++)
{
     dc.LineTo(20 + x[i], 600 - y1[i]);
     dc.FillSolidRect( 20 + x[i]-1,600- y1[i]-1, 3, 3, (COLORREF) 0xff00 );
}

(with the following, a warning message is outputted that says it triggered a breakpoint with respect to "dbgrptt.c - Debug CRT Reporting Functions" ??? So I must be missing or doing something wrong?

CImage myimage;

    myimage.GetDC();
    myimage.Save("C:\\Projects_example\\sweep.jpg");
    myimage.ReleaseDC();

Solution

  • CRect rc;
    GetClientRect(rc);
    CImage myimage;
    myimage.Create(rc.Width(), rc.Height(), 24);
    CDC memdc;
    memdc.CreateCompatibleDC(&dc);
    CBitmap * pOldBitmap = memdc.SelectObject(CBitmap::FromHandle((HBITMAP)myimage));
    memdc.BitBlt(0, 0, rc.Width(), rc.Height(), &dc, 0, 0, SRCCOPY);
    memdc.SelectObject(pOldBitmap);
    

    At this point your myimage object should have a copy of what was painted on the dc.