gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:35:57 31 4
gpt4 key购买 nike

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

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

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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com