在对话框里面添加WM_PAINT消息的响应函数OnPaint之后,在函数里面添加了一个CClientDC对象,然后运行之后就发现对话框直接卡死了。代码如下:
void CSettingDlg::OnPaint()
{
CClientDC dc(this);
CPen pen(m_nLineStyle, m_nLineWidth, m_clr);
CPen* pOldPen = dc.SelectObject(&pen);
CRect rect;
GetDlgItem(IDC_SAMPLE)->GetWindowRect(&rect);
ScreenToClient(rect);
dc.MoveTo(rect.left+20, rect.top + rect.Height() / 2);
dc.LineTo(rect.right-20, rect.top + rect.Height() / 2);
dc.SelectObject(pOldPen);
}
后来在网上查找原因,发现原来是在OnPaint函数里面只能使用CPaintDC,用其他DC类会一直触发WM_PAINT消息,从而无限调用OnPaint函数。其实类向导自动生成的OnPaint函数就有定义一个CPaintDC对象,我们只要使用这个现成的dc来绘图就好了。
MSDN里面对CPaintDC有这样的描述:
It performs a CWnd::BeginPaint at construction time and CWnd::EndPaint at destruction time.
A CPaintDC object can only be used when responding to a WM_PAINT message, usually in your OnPaint message-handler member function.