Search code examples
c++winapimacrosrgbgetpixel

COLORREF as RGB or hexadecimal


I have my current code that reads the GetPixel from the current cursor position but the return value is just some insane value by COLORREF and I want it to be in RGB. I looked into Microsoft Reference and I found RGB Macro

COLORREF RGB(
   BYTE byRed,
   BYTE byGreen,
   BYTE byBlue
);

and my question is how should I use the return from GetPixel into this RGB function and then print the value? Current code:

include <Windows.h>
include <wingdi.h> 
include <iostream>
pragma comment(lib, "gdi32.lib")

  int main() {
    while (true) {

      HDC hDC;
      hDC = GetDC(NULL);
      POINT p;
      GetCursorPos( & p);
      int cx = p.x;
      int cy = p.y;
      std::cout << GetPixel(hDC,cx,cy) << std::endl;
      Sleep(5);

    }

  }

Solution

  • The GetPixel() function returns a COLORREF which you can convert to a RGB value like this:

    COLORREF color = GetPixel(hdc, x, y);
    RGBTRIPLE rgb;
    
    rgb.rgbtRed = GetRValue(color);
    rgb.rgbtGreen = GetGValue(color);
    rgb.rgbtBlue = GetBValue(color);