Ok, finally got this working. For anyone else who is interested, here are the steps required to capture the image from a device context and render it into a Direct2D render target. In my case I wanted to capture the image from an MFC CDialogEx dialog window that had a bitmap background.
The first steps require the use of GDI to copy a bitmap from the dialog device context to a memory device context. This can be done using CreateCompatibleDC(), CreateCompatibleBitmap() and BitBlt(). I stored the resulting bitmap in an MFC CBitmap object.
The trick now is to get the bitmap into a ID2D1Bitmap object so that we can render it to the render target. This is achieved using the Windows Imaging Component (WIC).
First, call IWICImagingFactory::CreateBitmapFromHBITMAP(), passing in the CBitmap we created earlier. This will create an IWICBitmap object. The IWICBitmap object now needs to be converted to a 32bppPBGRA pixel format. This is done using a IWICFormatConverter object. Call IWICFormatConverter::Initialize() specifying the IWICBitmap object created previously.
Finally, call ID2D1RenderTarget::CreateBitmapFromWicBitmap(), passing in the IWICFormatConverter object created above. This will create an ID2D1Bitmap object that can now be drawn in the render target.
A snippet of code is shown below:
CClientDC dcParent(GetParent());
CRect rectClient;
CRect rectWindow;
CDC dcBackground;
CBitmap *pOldBitmap = NULL;
CBitmap DialogBitmap;
HRESULT hr = E_FAIL;
CComPtr<IWICBitmap> pDialogBitmap = NULL;
m_pParentBitmap.Release();
GetWindowRect(rectWindow);
GetParent()->ScreenToClient(rectWindow);
GetClientRect(rectClient);
dcBackground.CreateCompatibleDC(&dcParent);
DialogBitmap.CreateCompatibleBitmap(&dcParent, rectClient.Width(), rectClient.Height());
pOldBitmap = dcBackground.SelectObject(&DialogBitmap);
dcBackground.BitBlt(0, 0, rectClient.Width(), rectClient.Height(), &dcParent, rectWindow.left, rectWindow.top, SRCCOPY);
dcBackground.SelectObject(pOldBitmap);
hr = theApp.g_pWICFactory->CreateBitmapFromHBITMAP(DialogBitmap, NULL, WICBitmapIgnoreAlpha, &pDialogBitmap);
if (SUCCEEDED(hr))
{
CComPtr<IWICFormatConverter> pFormatConverter = NULL;
hr = pWICFactory->CreateFormatConverter(&pFormatConverter);
if (SUCCEEDED(hr))
{
hr = pFormatConverter->Initialize(pDialogBitmap,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.0f,
WICBitmapPaletteTypeCustom);
if (SUCCEEDED(hr))
{
hr = pRenderTarget->CreateBitmapFromWicBitmap(pFormatConverter, NULL, &m_pParentBitmap);
m_bParentBackgroundCaptured = true;
}
}
}