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;
}
Try to use GetClientRect
to get coordinates and MapWindowPoints
to transform it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With