Search code examples
c++windowswinapiscreen-capture

Capture Desktop Screen QT/C++ WinAPI


I'm using QT/C++ and I would like to capture the screen of my desktop and get the pixels buffer.

I'm using this function but it returns weird pixels values, can someone tell me why ?

void CaptureScreen()
{
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
HWND hDesktopWnd = GetDesktopWindow();
HDC hDesktopDC = GetDC(hDesktopWnd);
HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
HBITMAP hCaptureBitmap = CreateCompatibleBitmap(hDesktopDC, nScreenWidth, nScreenHeight);
SelectObject(hCaptureDC, hCaptureBitmap);

BitBlt(hCaptureDC, 0, 0, nScreenWidth, nScreenHeight, hDesktopDC, 0,0, SRCCOPY|CAPTUREBLT);

BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = nScreenWidth;
bmi.bmiHeader.biHeight = nScreenHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;

unsigned char *pPixels = new unsigned char[nScreenWidth * nScreenHeight * 4];

GetDIBits(hCaptureDC, hCaptureBitmap, 0, nScreenHeight, pPixels, &bmi,    DIB_RGB_COLORS);

for (int i = 0; i < 200; i++) {
    qDebug() << (int) pPixels[i];
}

delete[] pPixels;

ReleaseDC(hDesktopWnd, hDesktopDC);
DeleteDC(hCaptureDC);
DeleteObject(hCaptureBitmap);
}

Output is 1 1 1 255 1 1 1 255 ... but first pixels on the top of screen I have is white. It should be 255 255 255 255 etc...

Thank you !


Solution

  • Resolved! Thanks to RbMm comment :

    A bottom-up DIB is specified by setting the height to a positive number, while a top-down DIB is specified by setting the height to a negative number.
    
    the first line is bottom. if want another order use bmi.bmiHeader.biHeight = -nScreenHeight;
    

    I just replaced this line bmi.bmiHeader.biHeight = nScreenHeight; by this bmi.bmiHeader.biHeight = - nScreenHeight; and I get pixels from top line. It can help someone else :)