【问题标题】:How do I get the position of a control relative to the window's client rect?如何获取控件相对于窗口客户端矩形的位置?
【发布时间】:2010-12-29 09:21:12
【问题描述】:

我希望能够编写这样的代码:

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;
}

【问题讨论】:

  • 它是如何工作的,DirectX有什么用。 directx的新手。我做了我自己的功能来做到这一点
  • 是的,它是一个windows应用程序,因此使用了win32 api。

标签: c++ user-interface winapi


【解决方案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

【讨论】:

  • 这并不是真的有用,因为没有与您在 win32 中使用的“.Location”属性等效的属性(或者至少我没有找到)。
  • 我没用过win32。如果你有解决方案,请告诉我
【解决方案2】:

尝试使用GetClientRect获取坐标,使用MapWindowPoints对其进行变换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2017-10-22
    • 2013-08-04
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多