【发布时间】:2014-01-11 07:06:04
【问题描述】:
我正在尝试让我的程序截取屏幕截图,然后以可以从我的程序中轻松操作的方式格式化数据。
到目前为止,我提出了以下解决方案:
/**
* Creates a screenshot of the entire screen
* @param img - 2d array containing RGB values of screen pixels.
*/
void get_screenshot(COLORREF** img, const Rectangle &bounds)
{
// get the screen DC
HDC hdc_screen = GetDC(NULL);
// memory DC so we don't have to constantly poll the screen DC
HDC hdc_memory = CreateCompatibleDC(hdc_screen);
// bitmap handle
HBITMAP hbitmap = CreateCompatibleBitmap(hdc_screen, bounds.width, bounds.height);
// select the bitmap handle
SelectObject(hdc_memory, hbitmap);
// paint onto the bitmap
BitBlt(hdc_memory, bounds.x, bounds.y, bounds.width, bounds.height, hdc_screen, bounds.x, bounds.y, SRCPAINT);
// release the screen DC
ReleaseDC(NULL, hdc_screen);
// get the pixel data from the bitmap handle and put it into a nice data structure
for(size_t i = bounds.x; i < bounds.x + bounds.width; ++i)
{
for(size_t j = bounds.y; j < bounds.y + bounds.height; ++j)
{
img[j-bounds.y][i-bounds.x] = GetPixel(hdc_memory, i, j);
}
}
// release our memory DC
ReleaseDC(NULL, hdc_memory);
}
*注意:矩形实际上是我创建的一个结构体,其中包含 4 个size_t 字段,用于左上角 x 和 y 坐标,以及矩形的宽度和高度。它不是 WinAPI 矩形。
我对这段代码有几个问题:
- 我是否正确释放所有资源?
- 有没有更好的方法来做到这一点?我正在寻找与 RGB 值的二维数组具有相似复杂性和灵活性的东西。最终的屏幕捕获数据处理将使用 OpenCL 完成,因此我希望没有任何复杂的结构。
【问题讨论】:
标签: winapi visual-c++