dlg头文件中变量定义:
CString m_string;
RECT m_rect;
RECT rect_static;
SIZE size;
对话框初始化:
// TODO: Add extra initialization here
m_string = "ABCDEFGHIJK MFC 中 在一个对话框中 实现跑马灯";
SetTimer(1, 200, NULL); // 这里添加一个Timer
HWND hwnd = GetDlgItem(IDC_STATIC)->GetSafeHwnd();
HDC hdc = ::GetDC(hwnd);
::GetTextExtentPoint32(hdc, m_string, m_string.GetLength(), &size);
::GetClientRect(hwnd, &rect_static);
m_rect.left = rect_static.right;
m_rect.right = m_rect.left + size.cx;
m_rect.top = rect_static.top + (rect_static.bottom - rect_static.top - size.cy) / 2;
m_rect.bottom = m_rect.top + size.cy;
::ReleaseDC(hwnd, hdc);
TIMER响应函数:
// TODO: Add your message handler code here and/or call default
HWND hwnd = GetDlgItem(IDC_STATIC)->GetSafeHwnd();
HDC hdc = ::GetDC(hwnd);
HDC hmdc = ::CreateCompatibleDC(hdc);
HBITMAP hbitmap = ::CreateCompatibleBitmap(hdc, rect_static.right - rect_static.left, rect_static.bottom - rect_static.top);
HBITMAP holdbitmap = (HBITMAP)::SelectObject(hmdc, hbitmap);
DrawText(hmdc, m_string, m_string.GetLength(), &m_rect, DT_CENTER);
::BitBlt(hdc, 0, 0, rect_static.right-rect_static.left, rect_static.bottom-rect_static.top,
hmdc, 0, 0, SRCCOPY);
::SelectObject(hmdc, holdbitmap);
::DeleteObject(hbitmap);
::DeleteDC(hmdc);
::ReleaseDC(hwnd, hdc);
if (m_rect.right < rect_static.left)
{
m_rect.left = rect_static.right;
m_rect.right = m_rect.left + size.cx;
}
else
{
m_rect.left -= 10;
m_rect.right -= 10;
}
CDialog::OnTimer(nIDEvent);
朋友,谢谢你,我运行了,可以!但是我想知道为什么,你能把你定时器的那段代码给我详细注释下吗? 谢谢你了! 背景的颜色和文字颜色可以自己设置吗? 兄弟?
// TODO: Add your message handler code here and/or call default HWND hwnd = GetDlgItem(IDC_STATIC)->GetSafeHwnd(); //获取静态文本显示控件句柄 HDC hdc = ::GetDC(hwnd); //得到句柄的设备DC HDC hmdc = ::CreateCompatibleDC(hdc); //创建一个内存DC,和上面的设备DC兼容 HBITMAP hbitmap = ::CreateCompatibleBitmap(hdc, rect_static.right - rect_static.left, rect_static.bottom - rect_static.top); //创建一个位图用来在内存先绘制 HBITMAP holdbitmap = (HBITMAP)::SelectObject(hmdc, hbitmap); //将位图选入内存DC DrawText(hmdc, m_string, m_string.GetLength(), &m_rect, DT_CENTER); //绘制跑马灯文字 ::BitBlt(hdc, 0, 0, rect_static.right-rect_static.left, rect_static.bottom-rect_static.top, hmdc, 0, 0, SRCCOPY); //从内存复制到静态文本控件显示 ::SelectObject(hmdc, holdbitmap); //恢复旧环境 ::DeleteObject(hbitmap); //释放内存资源 ::DeleteDC(hmdc); ::ReleaseDC(hwnd, hdc); if (m_rect.right < rect_static.left) //如果文字从左边消失了,恢复到最右边 { m_rect.left = rect_static.right; m_rect.right = m_rect.left + size.cx; } else //否则左移10像素 { m_rect.left -= 10; m_rect.right -= 10; } 初始化对话框的时候,会得到文字绘制的矩形大小,具体你参考代码 这样用DrawText绘制的文字和背景是可以随便设置的,甚至可以透明背景…… 不过这些稍微麻烦点 有几个函数你查一下:SetTextColor SetBkColor 之类的 http://bbs.csdn.net/topics/240089273