How to use the BitBlt function to get pixel color on a screen or window using the Win32 API in C++

1 Answer

0 votes
#include <windows.h>
#include <iostream>

COLORREF GetPixelColor(int x, int y)
{
    // Get the screen DC
    HDC hScreenDC = GetDC(NULL);

    // Create a memory DC compatible with the screen
    HDC hMemDC = CreateCompatibleDC(hScreenDC);

    // Create a 1x1 bitmap to store the pixel
    HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, 1, 1);

    // Select the bitmap into the memory DC
    HGDIOBJ oldBitmap = SelectObject(hMemDC, hBitmap);

    // Copy the pixel from screen to memory DC
    BitBlt(hMemDC, 0, 0, 1, 1, hScreenDC, x, y, SRCCOPY);

    // Read the pixel from the memory DC
    COLORREF color = GetPixel(hMemDC, 0, 0);

    // Cleanup
    SelectObject(hMemDC, oldBitmap);
    DeleteObject(hBitmap);
    DeleteDC(hMemDC);
    ReleaseDC(NULL, hScreenDC);

    return color;
}

int main()
{
    int x_coordinate = 40, y_coordinate = 80;

    COLORREF color = GetPixelColor(x_coordinate, y_coordinate);

    int r = GetRValue(color);
    int g = GetGValue(color);
    int b = GetBValue(color);

    std::cout << "Pixel color at (" << x_coordinate << ", " << y_coordinate << "):\n";
    std::cout << "R = " << r << "\n";
    std::cout << "G = " << g << "\n";
    std::cout << "B = " << b << "\n";

    return 0;
}




/*
run

Pixel color at (40, 80):
R = 9
G = 0
B = 1

*/

 



answered Feb 17 by avibootz
...