MFC 将部分屏幕复制到 CBitmap 中

MFC copy part of the screen into a CBitmap

使用函数

OnEraseBkgnd(CDC* pDC)

我在派生的CDialog上写了class,填满屏幕的背景图片。

然后在 OnPaint 中,我有以下仅执行一次的代码(第一次调用 OnPaint)。

    GetInfoBarRect(&m_InfoBarRect);
    m_InfoBarBGBitmap.CreateCompatibleBitmap(&dc, m_InfoBarRect.Width(), m_InfoBarRect.Height() );

    bdc.CreateCompatibleDC(&dc);    
    pOldBitmap = bdc.SelectObject(&m_InfoBarBGBitmap);

    bdc.BitBlt (m_InfoBarRect.left, m_InfoBarRect.top, m_InfoBarRect.Width(),m_InfoBarRect.Height(), &dc, 0, 0, SRCCOPY);



    CImage image;
    image.Attach(m_InfoBarBGBitmap);
    image.Save(_T("C:\test.bmp"), Gdiplus::ImageFormatBMP);

    bdc.SelectObject(pOldBitmap);   
    bdc.DeleteDC();

以上代码,将屏幕的m_InfoBarRect部分复制到内存CBitmap中。

没有背景图片的部分,我只得到一个尺寸正确的空白填充矩形。

我的代码有问题吗?

我想你可能想要:

bdc.CreateCompatibleDC(&dc);    
pOldBitmap = bdc.SelectObject(&m_InfoBarBGBitmap);

dc.BitBlt (m_InfoBarRect.left, m_InfoBarRect.top, m_InfoBarRect.Width(),m_InfoBarRect.Height(), &bdc, 0, 0, SRCCOPY);

你从错误的坐标到错误的坐标。你的电话应该是

bdc.BitBlt( 0, 0, m_InfoBarRect.Width(), m_InfoBarRect.Height(), &dc,
            m_InfoBarRect.left, m_InfoBarRect.top, SRCCOPY);

相反,即从正确的源位置 (m_InfoBarRect.left/m_InfoBarRect.top) 到目标的原点 (0/0)。这是假设 GetInfoBarRect() returns 坐标来自与源 DC 相同的坐标系。