简体   繁体   English

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

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

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. 所以我有CWnd*指针指向控件,但根本找不到CWnd类中将检索给定控件的大小和位置的任何方法。 Any help? 有帮助吗?

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. GetWindowRect给出控件的屏幕坐标。 pDlg->ScreenToClient will then convert them be relative to the dialog's client area, which is usually what you need. pDlg->ScreenToClient然后将它们转换为相对于对话框的客户区域,这通常是您需要的。

Note: pDlg above is the dialog. 注意:上面的pDlg是对话框。 If you're in a member function of the dialog class, just remove the pDlg-> . 如果您在对话框类的成员函数中,只需删除pDlg->

In straight MFC/Win32: (Example of WM_INITDIALOG) 在直接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

Hope this helps! 希望这可以帮助! Happy coding :) 快乐编码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM