2010-04-16 66 views

回答

44
CRect rect; 
CWnd *pWnd = pDlg->GetDlgItem(YOUR_CONTROL_ID); 
pWnd->GetWindowRect(&rect); 
pDlg->ScreenToClient(&rect); //optional step - see below 

//position: rect.left, rect.top 
//size: rect.Width(), rect.Height() 

GetWindowRect給出了控件的屏幕座標。 pDlg->ScreenToClient然後將它們轉換爲相對於對話框的客戶區域,這通常是您需要的。

注意:pDlg上面是對話框。如果你在對話類的成員函數中,只需刪除pDlg->

+0

在官方文檔中說GetClientRect返回void,所以我不能使用pWnd-> GetClientRect(&rect)。如果我這樣做,我會得到運行時錯誤。 如果你使用GetClientRect(&rect),比我總是得到rect.left = 0和rect.top = 0,無論我把我的控件放在對話框的哪個位置! 它也寫在文檔中。 – 2010-04-16 13:52:46

+1

@kobac:你說得對(0,0) - 我現在修好了。關於運行時錯誤,'pWnd'指針可能無效。 void返回值不是問題,因爲我沒有在任何地方使用返回值。 – interjay 2010-04-16 14:03:20

5

在直MFC/Win32的:(WM_INITDIALOG的例子)

RECT r; 
HWND h = GetDlgItem(hwndDlg, IDC_YOURCTLID); 
GetWindowRect(h, &r); //get window rect of control relative to screen 
POINT pt = { r.left, r.top }; //new point object using rect x, y 
ScreenToClient(hwndDlg, &pt); //convert screen co-ords to client based points 

//example if I wanted to move said control 
MoveWindow(h, pt.x, pt.y + 15, r.right - r.left, r.bottom - r.top, TRUE); //r.right - r.left, r.bottom - r.top to keep control at its current size 

希望這有助於!快樂編碼:)

相關問題