How to get size and location of a control placed on a dialog in MFC?

dragan.stepanovic picture dragan.stepanovic · Apr 16, 2010 · Viewed 59.4k times · Source

I've got the pointer to the control with function

CWnd* CWnd::GetDlgItem(int ITEM_ID)

so i've got CWnd* pointer which points to the control, but simply can't find any method within CWnd class that will retrieve the size and location of a given control. Any help?

Answer

interjay picture interjay · Apr 16, 2010
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 gives the screen coordinates of the control. pDlg->ScreenToClient will then convert them be relative to the dialog's client area, which is usually what you need.

Note: pDlg above is the dialog. If you're in a member function of the dialog class, just remove the pDlg->.