How to find the position of a Win32 control in relation to its parent window?

The specified window handle is Win32, I need to find its position relative to its parent window.

I know several functions (for example, GetWindowRect()and GetClientRect()), but none of them explicitly return the required coordinates.

How to do it?

+25
source share
3 answers

The solution uses combined power GetWindowRect()and MapWindowPoints().

GetWindowRect() , . . MapWindowPoints() , , . "" , . - "" Windows, " ". Desktop HWND_DESKTOP, WinUser.h ( Windows.h). , Win32 GetParent(). , MapWindowPoints().

RECT YourClass::GetLocalCoordinates(HWND hWnd) const
{
    RECT Rect;
    GetWindowRect(hWnd, &Rect);
    MapWindowPoints(HWND_DESKTOP, GetParent(hWnd), (LPPOINT) &Rect, 2);
    return Rect;
}

MapWindowPoints() :

int MapWindowPoints(
  _In_     HWND hWndFrom,
  _In_     HWND hWndTo,
  _Inout_  LPPOINT lpPoints,
  _In_     UINT cPoints
);

MapWindowPoints() hWndFrom hWndTo. (HWND_DESKTOP) (GetParent(hWnd)). RECT (hWnd) .

+35

, , ( )

RECT rc;
GetClientRect(hWnd,&rc);
MapWindowPoints(hWnd,GetParent(hWnd),(LPPOINT)&rc,2);
+11

Here's a function that takes elements of both answers into something useful, especially to control the movement / change of coordinates.
It takes as parameters the integral control identifier from the resource and the handle of its container.
You should also consider whether it is minimized ownerHwndbefore calling a function by listening SIZE_MINIMIZEDin WM_SIZE.

BOOL ProcCtrl(int ctrlID, HWND ownerHwnd)
{
    RECT rcClient = {0};        
    HWND hwndCtrl = GetDlgItem(ownerHwnd, ctrlID);
    if (hwndCtrl)
    {
    GetWindowRect(hwndCtrl, &rcClient); //get window rect of control relative to screen
    MapWindowPoints(NULL, ownerHwnd, (LPPOINT)&rcClient,2);

    // Set scaling parameters to suit in either of the following functions
    //if (!MoveWindow(hwndCtrl, rcClient.left, rcClient.top, 
    //rcClient.right-rcClient.left, rcClient.bottom-rcClient.top, TRUE))
    {
        //Error;
        //return FALSE;
    }
    //if (!SetWindowPos(hwndCtrl, NULL, (int)rcClient.left, (int)(rcClient.top),
    //(int)(rcClient.right - rcClient.left), (int)(rcClient.bottom - rcClient.top), SWP_NOZORDER))
    {
        //Error;
        //return FALSE;
    }
    }
    else
    {
        //hwndCtrl Error;
        //return FALSE;
    }
    return TRUE;
}
0
source

All Articles