Find a pixel color in a window

Hi

I am trying to make a short program that seach for a specific color on a window en click on it.
The pixel is found with getPixel on window Device context, I move the mouse with setcursor to the corresponding coordinate and use mouse_event to generate a click.

Everything is fine except that the mouse is a little above (like 20 pixels) the correct colored pixel.

Here is the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    int i,j;

    COLORREF lColor;
    RECT lRect;
    POINT lPoint;

    HDC dc = GetDC(lTable);


    for(i=-lW/2+lX;i<lW/2+lX;i++)
    {
        for(j=-lH/2+lY;j<lH/2+lY;j++)
        {
            lColor = GetPixel(dc, i, j);
            printf("Color 0x%x\n",lColor);
            if( lSearchColor==lColor )
            {

                printf("Color found X=%d Y=%d\n",i,j);
                GetWindowRect(lTable,&lRect);
                GetCursorPos(&lPoint);


                SetCursorPos( lRect.left+i,lRect.top+j );
                mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, lRect.left+i, lRect.top+j, 0, 0);

                return 0;
            }
        }
    }


Does anybody knows why there is this offset between GetPixel output and absolute coordinates computed with window rect position?
Maybe it has anything to do with window's border.

Thanks
Fabien
I guess it may be something to do with border.
First of all.... you are calling GetDC but are never calling ReleaseDC. bad bad bad. Be sure to call ReleaseDC before you are done.

Secondly, what's the point of GetCursorPos on line 21? You never use it.

Then... to answer your actual question:
- GetDC gives you the DC of a window's client area. The client area is the main part of the window that the program draws its contents to. This does not include the window border, menu bar, title bar, status bar, etc.
- GetWindowRect gives you the window rectangle. The window includes all parts of the window... including the title bar, menu bar, etc, etc.

So your coordinate conversion code is wrong.


What you want is Client -> Screen coordinates. Fortunately, WinAPI offers a very simple ClientToScreen function, for just this purpose:

http://msdn.microsoft.com/en-us/library/windows/desktop/dd183434%28v=vs.85%29.aspx

1
2
3
4
5
6
7
8
9
// assuming i,j have the coords you want:

POINT cursor;
cursor.x = i;
cursor.y = j;

ClientToScreen(lTable, &cursor);

SetCursorPos( cursor.x, cursor.y );
Last edited on
Thx Disch.
I'll try that ASAP but I'm pretty cofident :-)

FYI I made the cleanup on the code I posted but in the original code I move back the mouse to its former position. Hence the GetCursorPos.
And I forgot to move up my releaseDC when I added the return 0.


Topic archived. No new replies allowed.