-2

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;
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64
ngmany
  • 7
  • 3
    Your code contains no error checking, so you have no idea whether it works or not. – Paul Sanders Feb 26 '22 at 23:29
  • You are not supposed to draw on DC like that. But assuming the windows and controls are standard Win32, call `ScreenToClient(hwnd_child, &pos);` immediately after `GetCursorPos`. And again, check to see `FindWindow` etc. succeeded. – Barmak Shemirani Feb 26 '22 at 23:52

1 Answers1

2

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);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770