c++mfcwidthcdialogcwnd

why do cx/cy from GetWindowRect(rcWindow2) differ from cx/cy fed into OnSize?


I want to get the cx and cy during OnInitDialog of a CDialog.

I can do this with the following code:

myDialog::OnInitDialog()
{
  CRect rcWindow2;
  this->GetWindowRect(rcWindow2);
  CSize m_szMinimum = rcWindow2.Size();
  int width = m_szMinimum.cx;
  int height = m_szMinimum.cy;
}

However, the cx and cy in the OnInitDialog is not the same as cx and cy which got into OnSize:

void myDialog::OnSize(UINT nType, int cx, int cy) 

From OnInitDialog: cx=417, cy=348

From OnSize : cx=401, cy=310

looks like might be the borders but i can't figure it out.

Suggestions as to how to get the same xy data in OnInitDialog as is fed into OnSize would be appreciated.


Inheritance:

myDialog -> CDialog -> CWnd


Solution

  • GetWindowRect returns window's Top-Left position in screen coordinates. Width and height of window includes border thickness and the height of the caption.

    GetClientRect always returns zero for Top-Left corner. Width and height is the same values as OnSize.

    While we are on the subject, this can also get confusing when it comes to moving child windows. Because SetWindowPos needs client coordinates, while GetWindowRect returns screen coordinates only. Screen/Client conversion will be needed like this:

    void GetWndRect(CRect &rc, HWND child, HWND parent)
    {
        GetWindowRect(child, &rc);
        CPoint offset(0, 0);
        ClientToScreen(parent, &offset); 
        rc.OffsetRect(-offset);
    }
    

    Now we can move a button in dialog box:

    CWnd *child = GetDlgItem(IDOK);
    CRect rc;
    GetWndRect(rc, child->m_hWnd, m_hWnd);
    rc.OffsetRect(-5, -5);
    child->SetWindowPos(0, rc.left, rc.top, 0, 0, SWP_NOSIZE);