我试图抓住窗口的图像来抓取像素数据。以下代码段在循环内运行。似乎一切正常,但运行几分钟后,应用程序开始挂起。我的猜测是存在某种内存泄漏。我希望有人能指出我在这里做错了什么。
void ScreenShot(LPCSTR filename)
{
RECT DesktopParams;
GetWindowRect(hwnd, &DesktopParams);
DWORD Width = DesktopParams.right - DesktopParams.left;
DWORD Height = DesktopParams.bottom - DesktopParams.top;
DWORD FileSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (sizeof(RGBTRIPLE) + 1 * (Width*Height * 4));
char *BmpFileData = (char*)GlobalAlloc(GMEM_FIXED, FileSize);
PBITMAPFILEHEADER BFileHeader = (PBITMAPFILEHEADER)BmpFileData;
PBITMAPINFOHEADER BInfoHeader = (PBITMAPINFOHEADER)&BmpFileData[sizeof(BITMAPFILEHEADER)];
BFileHeader->bfType = 0x4D42; // BM
BFileHeader->bfSize = sizeof(BITMAPFILEHEADER);
BFileHeader->bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
BInfoHeader->biSize = sizeof(BITMAPINFOHEADER);
BInfoHeader->biPlanes = 1;
BInfoHeader->biBitCount = 24;
BInfoHeader->biCompression = BI_RGB;
BInfoHeader->biHeight = Height;
BInfoHeader->biWidth = Width;
RGBTRIPLE *Image = (RGBTRIPLE*)&BmpFileData[sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)];
RGBTRIPLE color;
HDC CaptureDC = CreateCompatibleDC(DevC);
HBITMAP CaptureBitmap = CreateCompatibleBitmap(DevC, Width, Height);
SelectObject(CaptureDC, CaptureBitmap);
BitBlt(CaptureDC, 0, 0, Width, Height, DevC, 0, 0, SRCCOPY | CAPTUREBLT);
GetDIBits(CaptureDC, CaptureBitmap, 0, Height, Image, (LPBITMAPINFO)BInfoHeader, DIB_RGB_COLORS);
RGBTRIPLE *pixel = get_pixel(BInfoHeader, Image, 100, 100);
cout << (int)pixel->rgbtRed << ", " << (int)pixel->rgbtBlue << "," << (int)pixel->rgbtGreen << endl;
GlobalFree(BmpFileData);
}
经过一些测试后,我意识到,如果我注释掉get_pixel,那么它就会消失。
RGBTRIPLE * get_pixel(PBITMAPINFOHEADER BInfoHeader, RGBTRIPLE *Image, int x, int y)
{
return &Image[(BInfoHeader->biHeight - 1 - y)*BInfoHeader->biWidth + x];
}