16,472
社区成员
发帖
与我相关
我的任务
分享
void PaintWnd(CWnd * pWnd)
{
CDC * pWndDC = pWnd->GetWindowDC();
CRect WndRect = pWnd->GetWindowRect();
CDC MemDC;
CBitMap MemBitmap;
MemDC.CreateCompatibleDC(pWndDC); // 创建内存DC
MemBitmap.CreateCompatibleBitmap( // 创建兼容的位图
pWndDC,
WndRect.Width(),
WndRect.Height());
MemDC.SelectObject(MemBitmap); // 让内存DC输出到位图(我的理解就是选择画布)
// 使用MemDC画图
……
pWndDC->BitBlt(// 从内存DC复制到窗口DC
0,0,
WndRect.Width(),
WndRect.Height(),
&MemDC,
0,0,
SRCCOPY);
}
#pragma once
#include "Afxwin.h"
class CMemoryDC
{
public:
CMemoryDC(CDC *dc, RECT * rect,bool autoRender = false);
~CMemoryDC(void);
bool IsOK();
void Render(CDC * p_objectDC = NULL);
CDC* GetMemoryDC();
operator CDC * ();
private:
bool m_bAutoRender;
CRect m_DCRect;
CDC* m_pOriginalDC;
CDC m_MemoryDC;
CBitmap m_MemoryBmp;
};
#include ".MemoryDC.h"
CMemoryDC::CMemoryDC(CDC *dc, RECT * rect, bool autoRender)
{
m_bAutoRender = autoRender;
m_pOriginalDC = dc;
if (dc==NULL || rect==NULL)
return;
if (!m_MemoryDC.CreateCompatibleDC(dc))
return;
m_DCRect.SetRect(rect->left, rect->top, rect->right, rect->bottom);
if (!m_MemoryBmp.CreateCompatibleBitmap(dc, m_DCRect.Width(), m_DCRect.Height()))
return;
m_MemoryDC.SelectObject(m_MemoryBmp);
}
CMemoryDC::~CMemoryDC(void)
{
if (m_bAutoRender)
Render();
if (m_MemoryDC.m_hDC!=NULL)
m_MemoryDC.DeleteDC();
if (m_MemoryBmp.m_hObject!=NULL)
m_MemoryBmp.DeleteObject();
}
bool CMemoryDC::IsOK()
{
return m_MemoryDC.m_hDC!=NULL && m_MemoryBmp.m_hObject != NULL;
}
void CMemoryDC::Render(CDC * p_objectDC)
{
if (!IsOK())
return;
CDC * pDC = (p_objectDC==NULL ? m_pOriginalDC : p_objectDC);
CSize Size = m_MemoryDC.GetViewportExt() ;
pDC->BitBlt(
m_DCRect.left,
m_DCRect.top,
m_DCRect.Width(),
m_DCRect.Height(),
&m_MemoryDC,
0,0,
SRCCOPY);
}
CDC* CMemoryDC::GetMemoryDC()
{
return & m_MemoryDC;
}
CMemoryDC::operator CDC * ()
{
return & m_MemoryDC;
}
CRect Rect;
GetClientRect(Rect);
CPaintDC dc(this); // device context for painting
CMemoryDC MemDC(&dc, Rect, true);
if (MemDC.IsOK())
{
// 使用MemDC画窗口
}
// MemDC析构时会自动把图像复制到dc,无需其它操作
使用CMemoryDC创建内存DC防止窗口闪烁,编程的代码和不使用内存DC时相比,数量和复杂性几乎没有增加。