Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1066
  • Last Modified:

Getting screen pixel colour (Visual C++)

This is a Visual C++ question.
I was wondering if there is a way to the current pixel colour at the absolute position(x,y). i.e. Colour being displayed anywhere on the screen, not just the current program.
1 Solution
CWnd* pWnd = CWnd::GetDesktopWindow() ;
CDC* pDC = pWnd->GetDC() ;

COLORREF clr = pDC->GetPixel(100, 100) ;

pWnd->ReleaseDC(pDC) ;
just to show you in non MFC
HWND desktop = GetDesktopWindow();
HDC desktopHdc = GetDC(desktop);
COLORREF color = GetPixel(desktopHdc,1,1);

if you need to extract the rgb values then use this way
     int red,green,blue;

     COLORREF color = RGB(255,100,50);

     //COLORREF is stored as 0x00bbggrr, so..
     blue = (color/65536) & 255;
     green = (color/256) & 255;
     red = color & 255;

     cout<<"Red = "<<red;
     cout<<"\nGreen = "<<green;
     cout<<"\nBlue = "<<blue<<endl;
That doesn't seem to work for me, but the C way does

<<<<<<<<<<<<THIS WORKS

    HDC dc = GetDC(NULL);
    COLORREF result = GetPixel(dc, 700, 250);
    ReleaseDC(NULL, dc);


in the MFC version I get result as 0xffffffff (CLR_INVALID)

because per the documentation

"The return value is the RGB value of the pixel. If the pixel is outside of the current clipping region, the return value is CLR_INVALID."


<<<<<<<<<<<<<<<<<<<<THIS ALSO WORKS

    HDC dc = GetDC(NULL);
    CDC pDC;
    COLORREF clr = pDC.GetPixel(700, 250);


but the c version of

HWND wnd = GetDesktopWindow();
HDC dc = GetDC(wnd)


so it seems that there is something wrong with getting the desktop window and querying it for a color....

Priyesh:  if you know what is the equivelant in MFC for


The_FlashAuthor Commented:
Privesh, your code didn't seem to work on windows, only the desktop.
I modified it so it grabbed a window from it's position.

// Any point in which the window current occupies
Point * point(220,340);
CWnd * pWnd = WindowFromPoint( point );
CDC * dc = pWnd->GetDC();
COLORREF color = dc->GetPixel(51,173);

After a bit of frustration and testing, I found out that if it is a broswer window, which it what I was wanting it to work for, every object on the page is treated as a seperate window.
In the case that I was testing, there were 3 flash movies in the page, and each was treated as a different window.
The_FlashAuthor Commented:
I halved the points as it didn't give me the solution, although it did lead me o it.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now