1

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

Fractal
  • 1,748
  • 5
  • 26
  • 46
  • 2
    Yes, the difference is the border thickness and caption. Instead of `GetWindowRect`, use `GetClientRect` which corresponds `OnSize` values, it's the width and height of client area, it doesn't include non-client area, dialog borders and caption. – Barmak Shemirani Apr 14 '15 at 00:18
  • 2
    @BarmakShemirani That's correct and that should be an answer rather than a comment. – Roger Rowland Apr 14 '15 at 04:39
  • You are right Roger. For some reason I forgot the instructions about where to comment and where to answer. At least we are all in agreement :) – Barmak Shemirani Apr 14 '15 at 05:26
  • yes, if you put it as an answer, I'll mark it as the official answer. Thank you for the help Barmak. – Fractal Apr 14 '15 at 15:29
  • Thanks Fractal. I put in a long answer just to be different. – Barmak Shemirani Apr 15 '15 at 00:38

1 Answers1

3

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);
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77