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()
), but none of them explicitly return the desired coordinates.
How do I do this?
Iterate through child windows. Get the handles of all the windows that are currently open using the command: Set<String> allWindowHandles = driver. getWindowHandles(); which returns the set of handles. Use the SwitchTo command to switch to the desired window and also pass the URL of the web page.
A child window, owned by a parent form, is not a top-level form, because it has a parent. But it can be on top in the Z order, and can be modal or modeless depending on how it is displayed, with either ShowDiaglog() or Show() respectively.
A child window is a window that is launched and contained inside of a parent window. By definition, a child window is one that is dependent on a parent window and is minimized or closed when the parent minimizes or closes.
The solution is using the combined power of GetWindowRect()
and MapWindowPoints()
.
GetWindowRect()
retrieves the coordinates of a window relative to the entire screen area you see on your monitor. We need to convert these absolute coordinates into relative coordinates of our main window area. The MapWindowPoints()
transforms the coordinates given relative to one window into relative to another. So we need a "handle" of the screen area and the handle of the parent window of the control which we are trying to find coordinates of. The screen are is a "window" in Windows terminology and it is called "Desktop". We can access the handle of Desktop by the constant HWND_DESKTOP
defined in WinUser.h
(including Windows.h
is enough). And we can get the handle of our parent window simply by calling the Win32 function GetParent()
. Now we have all the parameters required to call the MapWindowPoints()
function.
RECT YourClass::GetLocalCoordinates(HWND hWnd) const { RECT Rect; GetWindowRect(hWnd, &Rect); MapWindowPoints(HWND_DESKTOP, GetParent(hWnd), (LPPOINT) &Rect, 2); return Rect; }
MapWindowPoints()
is defined as:
int MapWindowPoints( _In_ HWND hWndFrom, _In_ HWND hWndTo, _Inout_ LPPOINT lpPoints, _In_ UINT cPoints );
MapWindowPoints()
transform the coordinates relatively from hWndFrom
to hWndTo
. In our case, we do the transformation from Desktop (HWND_DESKTOP
) to our parent window (GetParent(hWnd)
). Therefore, the resulting RECT
structure holds the relative coordinates of our child window (hWnd
) relative to its parent window.
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