C++ 如何获取放置在 MFC 对话框中的控件的大小和位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2653130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get size and location of a control placed on a dialog in MFC?
提问by dragan.stepanovic
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?
所以我有CWnd*
指向控件的指针,但在CWnd
类中根本找不到任何方法来检索给定控件的大小和位置。有什么帮助吗?
回答by interjay
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.
GetWindowRect
给出控件的屏幕坐标。pDlg->ScreenToClient
然后将它们转换为相对于对话框的客户区,这通常是您需要的。
Note: pDlg
above is the dialog. If you're in a member function of the dialog class, just remove the pDlg->
.
注意:pDlg
上面是对话框。如果您在对话框类的成员函数中,只需删除pDlg->
.
回答by Jason Newland
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 :)
希望这可以帮助!快乐编码:)