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

23

我已经获得了指向函数的控件的指针。

CWnd* CWnd::GetDlgItem(int ITEM_ID)

我有一个指向控件的 CWnd* 指针,但是在 CWnd 类中找不到任何可以检索给定控件大小和位置的方法。 有什么帮助吗?


1
难道不是wnd->GetWindowRect(&rect)吗? - Sanjay Manohar
2个回答

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函数返回控件在屏幕上的坐标。然后通过调用pDlg->ScreenToClient函数将其转换为相对于对话框客户区域的坐标,通常这就是你想要的。

注意:上面的pDlg是对话框对象。如果你在对话框类的成员函数中,只需删除pDlg->即可。


1
在官方文档中,它说GetClientRect返回void,所以我不能使用pWnd->GetClientRect(&rect)。如果我这样做,就会出现运行时错误。 如果您使用GetClientRect(&rect),那么无论我在对话框上如何定位控件,都会始终得到rect.left=0和rect.top=0!这也写在文档中了。 - dragan.stepanovic
1
@kobac:你说得对,它返回了(0,0)-我现在已经修复了。关于运行时错误,pWnd指针可能无效。void返回值不是问题,因为我没有在任何地方使用返回值。 - interjay

6

在传统的 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

希望这能帮到你!愉快编程 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接