can't get getpixel from HWND

300 Views Asked by At

I am trying to get pixel color from hwnd

but it doesn't work

When I put "GetDC(NULL)" It worked

but "GetDC(hwnd_child)" is always 255,255,255.

please help

#include <iostream>
#include <Windows.h>

using namespace std;

int main() {

    POINT pos;
    int R;
    int G;
    int B;
    while (1) {    
        HWND  hwnd = FindWindow(NULL, L"LDPlayer"); //FindWindow(NULL, windowTitle);
        HWND hwnd_child = FindWindowEx(hwnd, NULL, L"RenderWindow", L"TheRender");
        HDC deviceContext1 = GetDC(hwnd_child );
        GetCursorPos(&pos);
        COLORREF color = GetPixel(deviceContext1, pos.x, pos.y);
        SetPixel(deviceContext1, pos.x, pos.y, RGB(255, 0, 0));
        R = GetRValue(color);
        G = GetGValue(color);
        B = GetBValue(color);
        std::cout << "x : " << pos.x << ", y : " << pos.y << ", R : " << R << ", G : " << G << ", B : " << B << endl;
        ReleaseDC(hwnd_child, deviceContext1);
      
        Sleep(1000);
    }

    return 0;
}
1

There are 1 best solutions below

0
Remy Lebeau On

Per the GetPixel() documentation:

The return value is the COLORREF value that specifies the RGB of the pixel. If the pixel is outside of the current clipping region, the return value is CLR_INVALID (0xFFFFFFFF defined in Wingdi.h).

GetCursorPos() returns screen coordinates, but you are retrieving an HDC for a child window. You need to convert the screen coordinates into client coordinates relative to the child window. You can use ScreenToClient() or MapWindowPoints() for that.

GetCursorPos(&pos);
ScreenToClient(hwnd_child, &pos);
COLORREF color = GetPixel(deviceContext1, pos.x, pos.y);
GetCursorPos(&pos);
MapWindowPoints(NULL, hwnd_child, &pos, 1);
COLORREF color = GetPixel(deviceContext1, pos.x, pos.y);