WTL中有兩個Mix-in類: CDoubleBufferImpl和CDoubleBufferWindowImpl,用於創建雙緩沖繪圖窗口,用法非常簡單。
下面創建了一個普通的WTL窗口類,在窗口的客戶區中有大量的繪圖工作,使用CDoubleBufferImpl類來消除繪圖時的閃爍現象:
代碼如下:
const COLORREF WHITE_COLOR = RGB(255,255,255);
const COLORREF BLUE_COLOR = RGB(0,0,255);
class CMainWindow :
public CWindowImpl<CMainWindow,CWindow,CSimpleWinTraits>,
public CDoubleBufferImpl<CMainWindow>
{
public:
typedef CMainWindow _thisClass;
typedef CDoubleBufferImpl<_thisClass> _baseDblBufImpl;
BEGIN_MSG_MAP(CMainWindow)
MSG_WM_CREATE(OnCreate)
MSG_WM_DESTROY(OnDestroy)
CHAIN_MSG_MAP(_baseDblBufImpl)
END_MSG_MAP()
int OnCreate(LPCREATESTRUCT lpCreateStruct)
{
m_RectPen.CreatePen(PS_SOLID,1,BLUE_COLOR);
return 0;
}
void OnDestroy()
{
PostQuitMessage(0);
}
void OnPaint(CDCHandle)
{
CPaintDC dc(m_hWnd);
DoPaint(dc.m_hDC);
}
void DoPaint(CDCHandle dc)
{
CRect rc;
GetClientRect(&rc);
dc.FillRect(&rc,WHITE_COLOR);
HPEN hOldPen = dc.SelectPen(m_RectPen);
const int width = 5;
int x = 0;
int count = rc.Width()/width;
int height = 0;
for (int i=0; i<count; i++)
{
height = (int)((double)rand()*rc.Height())/RAND_MAX;
dc.Rectangle(x,rc.Height(),x+width,rc.Height()-height);
x += width;
}
dc.SelectPen(hOldPen);
}
/*
void DoPaint(CDCHandle dc)
{
CRect rc;
GetClientRect(&rc);
int width = rc.Width(), height = rc.Height();
//use GDI+ to draw in the client area
Graphics g(dc.m_hDC);
SolidBrush whiteBrush(Color(255,255,255));
g.FillRectangle(&whiteBrush,0,0,width,height);
Pen bluePen(Color(0,0,255));
const int dx = 5;
int count = width/dx;
int x = 0, y = 0, h = 0;
for (int i=0;i<count;i++)
{
h = ((double)rand()*height)/RAND_MAX;
g.DrawRectangle(&bluePen,x,y,dx,h);
x += dx;
}
}
*/
private:
CPen m_RectPen;
};
值得一提的是,Windows Vista操作系統增加了對Double buffered paint的內建支持,這裡有一篇文章介紹
如何在Win32程序中使用這些API:
Using Windows Vista Built-In Double Buffering
在WTL中使用Vista提供的這一功能非常容易,最新的WTL庫中提供了CBufferedPaintImpl和CBufferedPaintWindowImpl兩個類,這兩個類的用法和前面提到的兩個WTL自帶的雙緩沖類幾乎一樣。區別僅僅是所重載的DoPaint()函數的參數稍有不同。
對於CBufferedPaintImpl類,所需重載的DoPaint()函數的樣子如下所示:
代碼如下:
void DoPaint(CDCHandle dc, RECT& rect)
{
CRect rc(rect);
dc.FillSolidRect(&rc,WHITE_COLOR);
HPEN hOldPen = dc.SelectPen(m_RectPen);
const int width = 5;
int x = 0;
int count = rc.Width()/width;
int height = 0;
for (int i=0; i<count; i++)
{
height = (int)((double)rand()*rc.Height())/RAND_MAX;
dc.Rectangle(x,rc.Height(),x+width,rc.Height()-height);
x += width;
}
dc.SelectPen(hOldPen);
}