如何获取控件相对于窗口客户端rect的位置?

时间:2009-12-23 06:21:27

标签: c++ user-interface winapi

我希望能够编写如下代码:

HWND hwnd = <the hwnd of a button in a window>;
int positionX;
int positionY;
GetWindowPos(hwnd, &positionX, &positionY);
SetWindowPos(hwnd, 0, positionX, positionY, 0, 0, SWP_NOZORDER | SWP_NOSIZE);

让它无所作为。但是,我无法弄清楚如何编写GetWindowPos()函数,以正确的单位给出答案:

void GetWindowPos(HWND hWnd, int *x, int *y)
{
    HWND hWndParent = GetParent(hWnd);

    RECT parentScreenRect;
    RECT itemScreenRect;
    GetWindowRect(hWndParent, &parentScreenRect);
    GetWindowRect(hWnd, &itemScreenRect);

    (*x) = itemScreenRect.left - parentScreenRect.left;
    (*y) = itemScreenRect.top - parentScreenRect.top;
}

如果我使用这个函数,我得到的坐标相对于父窗口的左上角,但是SetWindowPos()想要相对于标题栏下方区域的坐标(我假设这是“客户区“,但win32术语对我来说有点新鲜。)

解决方案 这是有效的GetWindowPos()函数(感谢Sergius):

void GetWindowPos(HWND hWnd, int *x, int *y)
{
    HWND hWndParent = GetParent(hWnd);
    POINT p = {0};

    MapWindowPoints(hWnd, hWndParent, &p, 1);

    (*x) = p.x;
    (*y) = p.y;
}

2 个答案:

答案 0 :(得分:17)

尝试使用GetClientRect获取坐标,并使用MapWindowPoints进行转换。

答案 1 :(得分:1)

我想你想要那样的东西。我不知道找到控件很热。 这段代码根据表格的大小将标签的位置分配在窗口中心的位置。

AllignLabelToCenter(lblCompanyName, frmObj)


 Public Sub AllignLabelToCenter(ByRef lbl As Label, ByVal objFrm As Form)
        Dim CenterOfForm As Short = GetCenter(objFrm.Size.Width)
        Dim CenterOfLabel As Short = GetCenter(lbl.Size.Width)
        lbl.Location = New System.Drawing.Point(CenterOfForm - CenterOfLabel, lbl.Location.Y)
    End Sub
    Private ReadOnly Property GetCenter(ByVal obj As Short)
        Get
            Return obj / 2
        End Get
    End Property