2009-12-23 33 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

相關問題