Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the position of a control relative to the window's client rect?

I want to be able to write code like this:

HWND hwnd = <the hwnd of a button in a window>;
int positionX;
int positionY;
GetWindowPos(hwnd, &positionX, &positionY);
SetWindowPos(hwnd, 0, positionX, positionY, 0, 0, SWP_NOZORDER | SWP_NOSIZE);

And have it do nothing. However, I can't work out how to write a GetWindowPos() function that gives me answers in the correct units:

void GetWindowPos(HWND hWnd, int *x, int *y)
{
    HWND hWndParent = GetParent(hWnd);

    RECT parentScreenRect;
    RECT itemScreenRect;
    GetWindowRect(hWndParent, &parentScreenRect);
    GetWindowRect(hWnd, &itemScreenRect);

    (*x) = itemScreenRect.left - parentScreenRect.left;
    (*y) = itemScreenRect.top - parentScreenRect.top;
}

If I use this function, I get coordinates that are relative to the top-left of the parent window, but SetWindowPos() wants coordinates relative to the area below the title bar (I'm presuming this is the "client area", but the win32 terminology is all a bit new to me).

Solution This is the working GetWindowPos() function (thanks Sergius):

void GetWindowPos(HWND hWnd, int *x, int *y)
{
    HWND hWndParent = GetParent(hWnd);
    POINT p = {0};

    MapWindowPoints(hWnd, hWndParent, &p, 1);

    (*x) = p.x;
    (*y) = p.y;
}
like image 523
Andy Avatar asked Dec 23 '09 06:12

Andy


1 Answers

Try to use GetClientRect to get coordinates and MapWindowPoints to transform it.

like image 79
Sergey Podobry Avatar answered Sep 26 '22 23:09

Sergey Podobry