I would add error checking to make sure the
FindWindow
and
GetDC
calls actually work. I tried using
FindWindow
and I couldn't get it to work for me.
I ended up writing a little class that calls
EnumWindows
and uses a callback function that calls
GetWindowText
. That worked for me. Here is the code I used :
class FindWin
{
public:
FindWin( PCSTR text, bool partial=true );
virtual bool Find()
{
m_Found = false;
if( m_Text && * m_Text )
EnumWindows( EnumFunc, (LPARAM)this );
return m_Found;
}
HWND GetWnd() { return m_hWnd; }
protected:
BOOL Matches( HWND hwnd, PCSTR wintext );
static BOOL CALLBACK EnumFunc( HWND hwnd, LPARAM lParam );
protected:
PCSTR m_Text { nullptr };
size_t m_Length { 0 };
HWND m_hWnd { NULL };
bool m_Found { false };
bool m_Partial { false }; };
FindWin::FindWin( PCSTR text, bool partial )
{
m_Text = text;
m_Length = strlen( m_Text );
m_Partial = partial;
}
BOOL FindWin::Matches( HWND hwnd, PCSTR wintext )
{
if( m_Partial )
m_Found = strncmp( wintext, m_Text, m_Length ) == 0;
else
m_Found = strcmp( wintext, m_Text ) == 0;
if( m_Found )
m_hWnd = hwnd;
return (int) ! m_Found; }
BOOL CALLBACK FindWin::EnumFunc( HWND hwnd, LPARAM lParam )
{
FindWin * pew = (FindWin *)lParam;
char wtext[ MAX_PATH+4 ] = { 0 };
GetWindowText( hwnd, wtext, MAX_PATH );
return pew->Matches( hwnd, wtext );
}
Here is the code that uses this class :
void ReadPixelValue()
{
FindWin finder( "Microsoft Spy++" );
if( ! finder.Find() )
{
printf( "Error - unable to find window\n" );
return;
}
HWND hwnd = finder.GetWnd();
HDC hdc = ::GetDC( hwnd );
if( ! hdc )
{
printf( "Error - unable to obtain device context\n" );
return;
}
COLORREF color = GetPixel( hdc, 20, 20 );
printf( "pixel color is %06X\n", color );
}