我正在学习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);
}

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

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

最佳答案

您可以按以下方式更改代码以使用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,只要窗口句柄可用,它几乎可以在任何地方使用。

关于c++ - 为什么CDC::LineTo()无法在Visual C++ 2015 MFC对话框中绘制?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36491021/

10-13 09:02