How do I get the position of a control relative to the window's client rect?

13,124

Solution 1

Try to use GetClientRect to get coordinates and MapWindowPoints to transform it.

Solution 2

I think u want something like that. I don't know hot to find controls. This segment of code alligns position of a label in the center of window form according to the size of form.

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
Share:
13,124
Andy
Author by

Andy

Updated on June 13, 2022

Comments

  • Andy
    Andy almost 2 years

    I want to be able to write code like this:

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

    And have it do nothing. However, I can't work out how to write a GetWindowPos() function that gives me answers in the correct units:

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

    If I use this function, I get coordinates that are relative to the top-left of the parent window, but SetWindowPos() wants coordinates relative to the area below the title bar (I'm presuming this is the "client area", but the win32 terminology is all a bit new to me).

    Solution This is the working GetWindowPos() function (thanks 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;
    }
    
  • Andy
    Andy over 14 years
    That isn't really useful as there isn't an equivalent to the ".Location" property you are using in the win32 (or at least, none that I've found).
  • Shantanu Gupta
    Shantanu Gupta over 14 years
    i never used win32. In case u get a solution, plz let me know it too