数据更新显示的问题
新建一对话框工程 CMyDlg,成员变量 n,在CMyDlg::OnEraseBkgnd中设置一副背景图片,在OnButton() 变化n的值,在OnPaint()进行显示。预期只会显示最后一个数值,结果显示所有数值都叠加在一起。前一个数值没有被擦除是什么原因?
实际工程是一个串口通讯的软件,希望显示新数据的同时能擦除旧数据,简化问题同上。
void CMyDlg::OnButton()
{
// TODO: Add your control notification handler code here
for(int i=0;i<100;i++)
{
n++;
this->Invalidate(TRUE);
this->UpdateWindow();
}
}
void CMyDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CPaintDC dc(this);
CString str;
dc.SetBkMode(TRANSPARENT);
str.Format("%d",n);
dc.TextOut(100,30, str);
CDialog::OnPaint();
}
}
BOOL CMyDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
CPaintDC dc(this);
CRect rect;
GetClientRect(&rect);
CDC dcMem;
dcMem.CreateCompatibleDC(&dc);
CBitmap bmpBackGround;
bmpBackGround.LoadBitmap(IDB_CELL);
BITMAP bitmap;
bmpBackGround.GetBitmap(&bitmap);
this->MoveWindow(200,200,bitmap.bmWidth,bitmap.bmHeight);
CBitmap *pbmpOld=dcMem.SelectObject(&bmpBackGround);
dc.SetStretchBltMode(COLORONCOLOR) ;
dc.StretchBlt
(0,0,bitmap.bmWidth,bitmap.bmHeight,&dcMem,0,0,bitmap.bmWidth,bitmap.bmHeight,SRCCOPY);
dc.SetBkMode(TRANSPARENT);
return true;
// return CDialog::OnEraseBkgnd(pDC);
}