How to get a screen image into a memory buffer?

后端 未结 2 462
孤独总比滥情好
孤独总比滥情好 2020-12-22 09:41

I\'ve been searching for a pure WIN32 way of getting the image data of a screen into a buffer, for analysis of the objects in the image later... Sadly I haven\'t found any.

2条回答
  •  醉梦人生
    2020-12-22 10:06

    // get screen DC and memory DC to copy to
    HDC hScreenDC = GetDC(0);
    HDC hMemoryDC = CreateCompatibleDC(hScreenDC);
    
    // create a DIB to hold the image
    BITMAPINFO bmi = { 0 };
    bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
    bmi.bmiHeader.biWidth = GetDeviceCaps(hScreenDC, HORZRES);
    bmi.bmiHeader.biHeight = -GetDeviceCaps(hScreenDC, VERTRES);
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;
    LPVOID pBits;
    HBITMAP hBitmap = CreateDIBSection(hMemoryDC, &bmi, DIB_RGB_COLORS, &pBits, NULL, 0);
    
    // select new bitmap into memory DC
    HGDIOBJ hOldBitmap = SelectObject(hMemoryDC, hBitmap);
    
    // copy from the screen to memory
    BitBlt(hMemoryDC, 0, 0, bmi.bmiHeader.biWidth, -bmi.bmiHeader.biHeight, hScreenDC, 0, 0, SRCCOPY);
    
    // clean up
    SelectObject(hMemoryDC, hOldBitmap);
    DeleteDC(hMemoryDC);
    ReleaseDC(0, hScreenDC);
    
    // the image data is now in pBits in 32-bpp format
    // free this when finished using DeleteObject(hBitmap);
    

提交回复
热议问题