如何找到Win32控件/窗口相对于其父窗口的位置? [英] How do I find position of a Win32 control/window relative to its parent window?

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

问题描述

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

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

我知道一些功能(例如 GetClientRect() ),但它们都没有明确返回所需的坐标.

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

我该怎么做?

推荐答案

该解决方案使用了GetWindowRect()

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

GetWindowRect()检索相对于您在监视器上看到的整个屏幕区域的窗口坐标.我们需要将这些绝对坐标转换为我们主窗口区域的相对坐标. MapWindowPoints()将相对于一个窗口给定的坐标转换为相对于另一个窗口的坐标.因此,我们需要屏幕区域的句柄"和我们要查找其坐标的控件父窗口的句柄.屏幕是Windows术语中的窗口",称为桌面".我们可以通过WinUser.h中定义的常量HWND_DESKTOP访问Desktop的句柄(包括Windows.h就足够了).而且,只需调用Win32函数

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控件/窗口相对于其父窗口的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆