tags:

views:

259

answers:

2

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;
}
+1  A: 

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
Shantanu Gupta
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).
Andy
i never used win32. In case u get a solution, plz let me know it too
Shantanu Gupta
+4  A: 

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

Sergius