MFC计算字符串长度,获取字符长度

CClientDC dc(GetDlgItem(IDC_EDIT_ShowMsg));
CFont *pOldFont = dc.SelectObject(this->GetFont());
CRect rcShow;
GetDlgItem(IDC_EDIT_ShowMsg)->GetClientRect(rcShow);
int maxWidth = rcShow.Width() - 15;

CString strSpace;
CString strTmp;
strTmp.Format(_T("%s%s%s"), msg, strSpace, strTime);

SIZE size = {0};
while (size.cx < maxWidth)
{
	::GetTextExtentPoint32(dc.m_hDC, strTmp, strTmp.GetLength(), &size);
	strTmp.Format(_T("%s%s%s"), msg, strSpace, strTime);
	strSpace += _T(" ");
}
strMsg += strTmp + _T("\r\n");
dc.SelectObject(pOldFont);

一定要记得选入字体,不然计算的长度会不精确

猜你喜欢

转载自blog.csdn.net/tajon1226/article/details/89335366