Farooq Seedat
Farooq Seedat

Reputation: 189

cant get pixel color of window c++

im beginner in using windows.h library and getting info from windows etc. i have written a code to find the pixel color of any window . im not sure what im getting wrong .

#include <iostream>
#include <windows.h>

using namespace std;
COLORREF centerColor;
POINT cent;
int main()
{
    HWND hd = FindWindow(NULL, L"Untitled - Notepad");
    HDC hdc_ = GetDC(hd); 
    cent.x = 0;
    cent.y = 0;
    centerColor = GetPixel(hdc_, cent.x, cent.y);
    cout << centerColor;
}

Upvotes: 1

Views: 1034

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51815

Your code may be working (assuming you have the correct format of the Window name); it's just that you may not understand the format of a COLORREF object. Try this:

#include <iostream>
#include <windows.h>

using namespace std;
COLORREF centerColor;
POINT cent;
int main()
{
    HWND hd = FindWindow(NULL, L"Untitled - Notepad");
//  HWND hd = FindWindow(NULL, "Untitled - Notepad"); // Use this version if you are NOT using a Unicode build!
    HDC hdc_ = GetDC(hd);
    cent.x = 0;
    cent.y = 0;
    centerColor = GetPixel(hdc_, cent.x, cent.y);
//  cout << centerColor;
    cout << int(GetRValue(centerColor)) << " " << int(GetGValue(centerColor)) << " " << int(GetBValue(centerColor)) << endl;
    ReleaseDC(hd, hdc_); // You should call this when you've finised with the DC!
}

This shows the three R/G/B values for the pixel colour (255 255 255 is white).

EDIT: Try it, to see if you get 255 255 255 - then type some text in Notepad and select that text, then run your program again - should give a different colour!

It works for me!

Upvotes: 1

Related Questions