BitBlt仅捕获部分屏幕

时间:2015-11-12 10:31:02

标签: c++ windows gdi bitblt

我试图在Windows 10下使用GDI捕获屏幕的正方形部分。这就是我尝试的方式:

//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);

所以我将(sourceX, sourceY)的32x32像素矩形捕获到位图中并将其绘制到屏幕上(左上角)。

然而,这导致大多数黑色方块。只有在被捕获之前由GDI绘制的东西才被捕获。我很确定第一个BitBlt是问题所在。如果我指定WHITENESS作为最后一个参数,我会得到一个白色正方形,这是我所期望的。因此从屏幕到位图的捕获似乎是有问题的。

如果我使用

直接从屏幕复制到屏幕
BitBlt(desktop, 0, 0, 32, 32, desktop, sourceX, sourceY, SRCCOPY);

,一切都按预期工作。

我也试过了旗帜CAPTUREBLT

如何将整个区域捕获到位图中?

1 个答案:

答案 0 :(得分:3)

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