【问题标题】:How to get size and location of a control placed on a dialog in MFC?如何获取放置在 MFC 对话框中的控件的大小和位置?
【发布时间】:2011-02-08 20:02:51
【问题描述】:

我有指向带有函数的控件的指针

CWnd* CWnd::GetDlgItem(int ITEM_ID)

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

【问题讨论】:

  • 不是 wnd->GetWindowRect(&rect) 吗?

标签: c++ mfc


【解决方案1】:
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->

【讨论】:

  • 在官方文档中说 GetClientRect 返回 void,所以我不能使用 pWnd->GetClientRect(&rect)。如果这样做,我会收到运行时错误。如果您使用 GetClientRect(&rect),那么无论我将控件放在对话框的哪个位置,我总是得到 rect.left=0 和 rect.top=0!它也写在文档中。
  • @kobac:你说得对,它返回 (0,0) - 我现在修好了。关于运行时错误,pWnd 指针可能无效。 void 返回值不是问题,因为我没有在任何地方使用返回值。
【解决方案2】:

在直接 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

希望这会有所帮助!快乐编码:)

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    相关资源
    最近更新 更多