I am trying to capture a square part of the screen using GDI under Windows 10. This is how I tried:
//Get screen DC
desktop = GetDC(NULL);
//Create a compatible bitmap of 32 x 32 px.
HDC hCaptureDC = CreateCompatibleDC(desktop);
HBITMAP captureBmp = CreateCompatibleBitmap(hCaptureDC, 32, 32);
SelectObject(hCaptureDC, captureBmp);
//loop:
BitBlt(hCaptureDC, 0, 0, 32, 32, desktop, sourceX, sourceY, SRCCOPY);
BitBlt(desktop, 0, 0, 32, 32, hCaptureDC, 0, 0, SRCCOPY);
So I capture a 32x32 px rectangle at (sourceX, sourceY)
into the bitmap and draw it onto the screen (top left corner).
However, this results in mostly black squares. Only things that have been drawn by GDI before get captured. I am quite sure that the first BitBlt
is the problem. If I specify WHITENESS
as the last parameter, I get a white square, which is what I would expect. So the capturing from screen to the bitmap seems to be problematic.
If I copy directly from screen to screen using
BitBlt(desktop, 0, 0, 32, 32, desktop, sourceX, sourceY, SRCCOPY);
, everything works as expected.
I also tried the flag CAPTUREBLT
.
How can I capture the entire region into the bitmap?
This line
HBITMAP captureBmp = CreateCompatibleBitmap(hCaptureDC, 32, 32);
Should be
HBITMAP captureBmp = CreateCompatibleBitmap(desktop, 32, 32);
The reason is explained on the documentation page for CreateCompatibleBitmap
:
When a memory device context is created, it initially has a 1-by-1 monochrome bitmap selected into it. If this memory device context is used in CreateCompatibleBitmap, the bitmap that is created is a monochrome bitmap. To create a color bitmap, use the HDC that was used to create the memory device context