为什么CDC :: LineTo()在Visual C ++ 2015 MFC对话框中没有绘制?

时间:2016-04-08 03:30:05

标签: c++ mfc

我正在学习MFC而我试图在MFC基于对话框的应用程序主窗口上绘制一些行,这应该是一个相当简单的任务但是在运行时我看到对话框上没有画线。

以下是我写的方法:

// draw corner of a rectangle on specified device context
void CTestDrawCornerDlg::DrawCorner(
    CDC* pDC,
    const CornerType& type,
    const CPoint& position,
    const unsigned int& size
    )
{
    CPen pen(PS_SOLID, 5, RGB(0, 0, 0));
    CPen* pOldPen = pDC->SelectObject(&pen);

    CPoint pH, pV;
    // I could make following lines simply with a 2-lines block,
    //  but I'd leave it as it was to make it easier to understand.
    switch (type)
    {
    case LEFT_TOP:
        pH.x = position.x + size;
        pH.y = position.y;
        pV.x = position.x;
        pV.y = position.y + size;
        break;
    case LEFT_BOTTOM:
        pH.x = position.x - size;
        pH.y = position.y;
        pV.x = position.x;
        pV.y = position.y + size;
        break;
    case RIGHT_TOP:
        pH.x = position.x + size;
        pH.y = position.y;
        pV.x = position.x;
        pV.y = position.y - size;
        break;
    case RIGHT_BOTTOM:
        pH.x = position.x - size;
        pH.y = position.y;
        pV.x = position.x;
        pV.y = position.y - size;
        break;
    default: break;
    }
    pDC->MoveTo(position);
    pDC->LineTo(pH);
    pDC->MoveTo(position);
    pDC->LineTo(pV);

    pDC->SelectObject(pOldPen);
}

我在Dialog类的OnPaint方法中调用了这个方法:

void CTestDrawCornerDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
        // lines generated automatically when creating
        // MFC project are truncated for brevity
    }
    else
    {
        CDialogEx::OnPaint();
    }

    CPaintDC pDC(this);
    DrawCorner(&pDC, LEFT_TOP, CPoint(50, 50), 50);
}

我想这是一个新手的错误,但我不知道错误是什么。谢谢你的帮助!

P.S。请从以下链接下载MFC项目以重新创建此问题: https://www.dropbox.com/s/exeehci9kopvgsn/TestDrawCorner.zip?dl=0

1 个答案:

答案 0 :(得分:3)

您可以将代码更改为使用CDialogEx::OnPaint() + CClientDC,如下所示:

void CTestDrawCornerDlg::OnPaint()
{
    CDialogEx::OnPaint();
    CClientDC pDC(this);
    DrawCorner(&pDC, LEFT_TOP, CPoint(50, 50), 50);
}

或只使用CPaintDC

void CTestDrawCornerDlg::OnPaint()
{
    CPaintDC pDC(this);
    DrawCorner(&pDC, LEFT_TOP, CPoint(50, 50), 50);
}

但请勿使用OnPaint + CPaintDC

要查看问题,请注意在MFC中如何定义OnPaintCPaintDC

void CDialog::OnPaint()
{
    CPaintDC dc(this);
    if (PaintWindowlessControls(&dc))
       return;
    Default();
}

CPaintDC::CPaintDC(CWnd* pWnd)
{
    if (!Attach(::BeginPaint(m_hWnd = pWnd->m_hWnd, &m_ps)))
        AfxThrowResourceException();
}

::BeginPaint是WinAPI的核心功能。它只应在响应WM_PAINT时调用一次,并且不能在其他任何地方使用。

另一方面,

CClientDC使用::GetDC,只要窗口句柄可用,它就可以在任何地方使用。