在VC ++ MFC中绘制矩形的应用程序会为CDC对象创建错误

时间:2014-02-15 05:07:56

标签: visual-c++ visual-studio-2012 mfc

我想在点击按钮后在对话框中绘制一个矩形。要做到这一点,我写了以下代码,

void CAnalysisofasinglyreinforcedbeamDlg::OnBnClickedCalculate()
{
// TODO: Add your control notification handler code here
CDC *pdc = NULL;
this->DrawRect(pdc);    
}

void CAnalysisofasinglyreinforcedbeamDlg::DrawRect(CDC* pDC)
{
       // create and select a solid blue brush
       CBrush brushBlue(RGB(0, 0, 255));
       CBrush* pOldBrush = pDC->SelectObject(&brushBlue);

     // create and select a thick, black pen
    CPen penBlack;
    penBlack.CreatePen(PS_SOLID, 3, RGB(0, 0, 0));
    CPen* pOldPen = pDC->SelectObject(&penBlack);

    // get our client rectangle
   CRect rect;
   GetClientRect(rect);

   // shrink our rect 20 pixels in each direction
   rect.DeflateRect(20, 20);

   // draw a thick black rectangle filled with blue
   pDC->Rectangle(rect);

   // put back the old objects
    pDC->SelectObject(pOldBrush);
    pDC->SelectObject(pOldPen);
}

执行时的代码会出现以下错误

Unhandled exception at 0x59B7695B (mfc110ud.dll) in beam.exe: 0xC0000005: Access violation reading location 0x00000004.

我正在使用VS2012进行开发

1 个答案:

答案 0 :(得分:2)

您正在传递NULL显示上下文。试着这样做:

void CAnalysisofasinglyreinforcedbeamDlg::OnBnClickedCalculate()
{
    // draw on client dc
    CClientDC pDC(this);
    DrawRect(&pDC);    
}