如何获取放在MFC对话框中的控件的大小和位置?

dra*_*vic 21 c++ mfc

我已经通过函数获得了控件的指针

CWnd* CWnd::GetDlgItem(int ITEM_ID)
Run Code Online (Sandbox Code Playgroud)

所以我有CWnd*指向控件的指针,但是在CWnd类中找不到任何能够检索给定控件的大小和位置的方法.有帮助吗?

int*_*jay 47

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()
Run Code Online (Sandbox Code Playgroud)

GetWindowRect给出控件的屏幕坐标.pDlg->ScreenToClient然后将它们转换为相对于对话框的客户区域,这通常是您需要的.

注意:pDlg上面是对话框.如果您在对话框类的成员函数中,只需删除pDlg->.


Jas*_*and 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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!快乐编码:)