相对于其父窗口的位置

相对于其父窗口的位置

本文介绍了如何找到 Win32 控件/窗口相对于其父窗口的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 Win32 窗口的句柄,我需要找到它相对于其父窗口的位置.

Given handle of a Win32 window, I need to find position of it relative to its parent window.

我知道几个函数(例如;GetWindowRect()GetClientRect()),但它们都没有明确返回所需的坐标.

I know several functions (e.g.; GetWindowRect() and GetClientRect()), but none of them explicitly return the desired coordinates.

我该怎么做?

推荐答案

解决方案是结合使用 GetWindowRect()MapWindowPoints().

The solution is using the combined power of GetWindowRect() and MapWindowPoints().

GetWindowRect() 检索窗口相对于您在监视器上看到的整个屏幕区域的坐标.我们需要将这些绝对坐标转换成我们主窗口区域的相对坐标.MapWindowPoints() 将给定的相对于一个窗口的坐标转换为相对于另一个窗口的坐标.所以我们需要一个屏幕区域的句柄"和我们试图找到坐标的控件的父窗口的句柄.屏幕是 Windows 术语中的窗口",称为桌面".我们可以通过WinUser.h(包括Windows.h)中定义的常量HWND_DESKTOP来访问Desktop的句柄.我们可以通过调用 Win32 函数来获取父窗口的句柄 GetParent().现在我们拥有调用 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() 定义为:

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

MapWindowPoints() 将坐标从 hWndFrom 相对转换为 hWndTo.在我们的例子中,我们进行了从桌面(HWND_DESKTOP)到我们的父窗口(GetParent(hWnd))的转换.因此,生成的 RECT 结构保存了我们的子窗口 (hWnd) 相对于其父窗口的相对坐标.

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.

这篇关于如何找到 Win32 控件/窗口相对于其父窗口的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 15:57