2009-12-23 61 views
16

我希望能够写出这样的代码:如何获得控件相对于窗口客户端矩形的位置?

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()功能(感谢谢尔盖):

​​
+0

它是一个窗口应用程序 – 2009-12-23 06:24:51

+0

它是如何工作的,DirectX有什么用处。新手在directx。我做了我自己的功能 – 2009-12-23 06:26:05

+0

是的,它是一个Windows应用程序,因此使用win32 api。 – Andy 2009-12-23 06:43:49

回答

17

尝试使用GetClientRect得到坐标和MapWindowPoints改造它。

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 
+0

这不是很有用,因为没有与您在win32中使用的“.Location”属性等效(或者至少没有找到)。 – Andy 2009-12-23 06:45:17

+0

我从来没有使用win32。如果你得到解决方案,请让我知道它 – 2009-12-23 07:04:18

相关问题