23

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?

Naveen
  • 74,600
  • 47
  • 176
  • 233
dragan.stepanovic
  • 2,955
  • 8
  • 37
  • 66

2 Answers2

54
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->.

interjay
  • 107,303
  • 21
  • 270
  • 254
  • 1
    In official documentation it says that GetClientRect returns void, so I can't use pWnd->GetClientRect(&rect). If I do, I get runtime error. If you use GetClientRect(&rect), than I always get rect.left=0 and rect.top=0, no matter where I position my control on a dialog! It's also written in documentation. – dragan.stepanovic Apr 16 '10 at 13:52
  • 1
    @kobac: You're right about it returning (0,0) - I fixed it now. Regarding the runtime error, the `pWnd` pointer was probably invalid. The void return value is not a problem since I'm not using the return value anywhere. – interjay Apr 16 '10 at 14:03
6

In straight MFC/Win32: (Example of 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

Hope this helps! Happy coding :)

Jason Newland
  • 481
  • 5
  • 3