I'm trying to make a C++ code that prints the rgb value of pixel where mouse cursor is every second. I used GetDC(NULL) for HDC of desktop, GetCursorPos(&pos) for the position of mouse cursor, getPixel(hDC, pos.x, pos.y) for the RGB value of the pixel that the mouse cursor points.
Here is my full C++ code.
#include <iostream>
#include <Windows.h>
using namespace std;
int main(){
POINT pos;
int R;
int G;
int B;
while (1) {
GetCursorPos(&pos);
HDC hDC = GetDC(NULL);
COLORREF color=GetPixel(hDC, pos.x, pos.y);
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(NULL, hDC);
Sleep(1000);
}
return 0;
}
When I compiled this, it prints the rgb value of some pixel every second, however, the pixel doesn't match the pixel where mouse is on. At first, I just thought that the client of some window may have different point, or the total number of pixels in my laptop is less than 1920x1080 (it's actually 1536x864), so there may be a bug, and it could be solved by just translating the point.
But although for some points, it did work, but most points, it didn't work.
And I tried some test. (The code is compiled using visual studio 2017.)
While the code running, I dragged the console window by mouse. (Note that the console window's Non-client window is almost white. i.e. the RGB value is (255, 255, 255). ) So, the relative position of mouse cursor on the console window doesn't change. However, the printed rgb value changed!
I suggest that it may be related to the ppi, but I don't know why exactly.
What should I do and know to get the rgb value of pixel that the mouse cursor points?