WM_SIZE problem

Hi:
i just begin to learn MFC,and i got a problem about WM_SIZE message.i start a new VC6 MFC Wizard project ,use all the defaul setting of the App wizard,except it is a single doc project,and the base class of the CTestView class is CFormView instead of CView.after the frame work is constructed ,i add a control to the form view,whatever control,say a button,whose id is IDC_BTN_TEST.i'd like to keep the size of the button the same with the client rect of the view,then i add the following code to the view's OnSize message handler.

CODE

void CTestView::OnSize(UINT nType, int cx, int cy)
{
CFormView::OnSize(nType, cx, cy);

// TODO: Add your message handler code here
CWnd *pButton;
RECT rect;

pButton=GetDlgItem(IDC_BTN_TEST);
GetClientRect(&rect);
pButton->MoveWindow(&rect);
}


there is no compile error or warning ,but when i run it ,it crashes.

but when i change the code like fowlling it works .

CODE

void CTestView::OnSize(UINT nType, int cx, int cy)
{
CFormView::OnSize(nType, cx, cy);

// TODO: Add your message handler code here
CWnd *pButton;
RECT rect;
static int iFlag=0;

if(iFlag>2){
pButton=GetDlgItem(IDC_BTN_TEST);
GetClientRect(&rect);
pButton->MoveWindow(&rect);
}
iFlag++;
}


it seems on the first several call of the handler,the buttton control is not constructed or valid yet.but i don't know the exactly reason,any one can help me ,thanks in advance.
[1638 byte] By [JumboGeng] at [2007-12-16]
# 1
The problem is that the first WM_SIZE message is set when you button is not created. So GetDlgItem returns a NULL pointer. Just change you code in this way:

void CTestView::OnSize(UINT nType, int cx, int cy)
{
CFormView::OnSize(nType, cx, cy);

CWnd *pButton;
if (pButton=GetDlgItem(IDC_BTN_TEST))
{
RECT rect;
GetClientRect(&rect);
pButton->MoveWindow(&rect);
}
}


So the repositioning of the button only occurs if its already there.

Using GetDlgItem without error checking is no good style. There is always a chance that windows don't get created.

MartinRichter at 2007-9-9 > top of Msdn Tech,Visual C#,Visual C# General...