Given handle of a Win32 window, I need to find position of it relative to its parent window.
I know several functions (e.g.; GetWindowRect() and GetClientRect()), bu
Here's a very basic typedef struct based on the above answers:
typedef struct tagRectCl {
static RECT rectOut;
RECT RectCl(int ctrlID, HWND &hwndCtrl, HWND &ownerHwnd)
{
RECT rectIn;
GetWindowRect(hwndCtrl, &rectIn); //get window rect of control relative to screen
MapWindowPoints(NULL, ownerHwnd, (LPPOINT)&rectIn, 2);
rectOut = rectIn;
return rectOut;
}
RECT RectCl(int ctrlID)
{
// for rectOut already populated
return rectOut;
}
};
}RectCl;
RECT RectCl::rectOut = {};
The idea being to extend ctrlID over a range of controls, where the storage for the corresponding rectOut
s can be considered for a more accommodating structure.
Usage: the following returns the converted rect:
RECT rect1 = RectCl().RectCl(IDC_CTRL1, hWndCtrl, hWndOwner);
The following is a partly coded function that takes elements of both answers into something usable for dialogs - particularly for move/resizing control co-ordinates, the original reason for landing at this page.
It accepts as parameters an integral control ID from a resource or HMENU
item from CreateWindow
, and a handle for its container.
One should also consider whether ownerHwnd
is minimized before calling the function by listening for SIZE_MINIMIZED
in 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 extra scaling parameters here 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;
}