I am working on a project where I have to read the color of a pixel on screen with CreateCompatibleBitmap and Bitblt. Unfortunately this method is pretty slow, I am getting times of around 60 to 100 ms in a loop. I use this code:
HDC hdc = GetDC(NULL), hdcMem = CreateCompatibleDC(hdc);
HBITMAP hBitmap = CreateCompatibleBitmap(hdc, ScreenX, ScreenY);
BITMAPINFOHEADER bmi = { 0 };
bmi.biSize = sizeof(BITMAPINFOHEADER);
bmi.biPlanes = 1;
bmi.biBitCount = 24;
bmi.biWidth = ScreenX;
bmi.biHeight = -ScreenY;
bmi.biCompression = BI_RGB;
SelectObject(hdcMem, hBitmap);
BitBlt(hdcMem, 0, 0, ScreenX, ScreenY, hdc, 0, 0, SRCCOPY);
GetDIBits(hdc, hBitmap, 0, ScreenY, ScreenData, (BITMAPINFO*)&bmi, DIB_RGB_COLORS);
DeleteObject(hBitmap);
DeleteDC(hdcMem);
ReleaseDC(NULL, hdc);
Most of the time (95%) is spent in the Bitblt function. I have read that it takes so long because Bitblt has to convert the color formats but I dont understand how I can avoid that...
I use Windows 11 and my screen res is FHD 1920x1080
Any suggestions how I could speed this program up?
You can use
CreateDIBSectionto create a kind of bitmap that gives you access to the pixel data rather than creating a regular "compatible" bitmap and then copying the pixel data into a buffer usingGetDIBitsbut I ran a benchmark of doing it this way and the time saving is there but it is not substantial. I get about a 10% speed improvement, which is not much.Code below, and I did write this fast so may have made a mistake. The point of the variable
dummyin the following is so that everything does not get optimized away because there is not output.