写wince程序寻得的中文文字换行加折行的方法:
void loadTxtWordBreak(HDC hdc,RECT rect)//按行读取txt文件 { CString sAll, sLine; CString sWholePath; USHORT i; HANDLE hFile; DWORD NumberOfBytesRead; BOOL bSuccess; sWholePath = "\\hotMessage.txt"; sWholePath = dirFile; hFile = CreateFile(sWholePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); DWORD filesize=GetFileSize(hFile,NULL); char* ReadBuffer=new char[filesize+1]; // 最后一位为 '/0',C-Style 字符串的结束符。 bSuccess = ReadFile(hFile, ReadBuffer, filesize, &NumberOfBytesRead, NULL); ReadBuffer[NumberOfBytesRead] = '\0'; sAll = ReadBuffer; sLine = ""; for (i = 0; i < sAll.GetLength(); i++) { sLine += sAll.GetAt(i); if ((sAll.GetAt(i) == '\n') || (i == sAll.GetLength() - 1)) { if (sLine.Right(2) == "\r\n") { sLine = sLine.Left(sLine.GetLength() - 2); //去掉 \r\n } if (sLine != "") { DrawTextEx(hdc,sLine, &rect); } sLine = ""; } } // 善后工作 delete[] ReadBuffer; // 注意是delete[] 而不是 delete CloseHandle(hFile); // 关闭句柄。 } int DrawTextEx(HDC hDC,CString sText, LPRECT lpRect)//读取每行并按宽度折行 { int nCount,nLine; CString sDraw,sLeft; sDraw.Empty(); sLeft=sText; LPCTSTR lpString=sText; int nTolLength=sText.GetLength(); UINT uFormat=DT_SINGLELINE | DT_CENTER; SIZE szStr; CString lpStr; int nWidth = lpRect->right - lpRect->left; // Rect width nCount =1; nLine = 1; while(nTolLength>0) { //如果绘制的字字符串本身带有格式,有换行符。这里需将nCount置于1。要遍历每个字符是否为换行符 //nCount=1; if(nCount>nTolLength) nCount=nTolLength; lpStr=sLeft.Left(nCount); GetTextExtentPoint32(hDC, lpStr, nCount, &szStr); if(szStr.cx < nWidth) { while(szStr.cx < nWidth && nCount <nTolLength)//判断字符长度是否超过输出面板最大宽度,如果没超过判断再加一个字是否超过 { nCount++; lpStr=sLeft.Left(nCount); GetTextExtentPoint32(hDC, lpStr, nCount, &szStr);//该函数计算指定的正文字符串的高度和宽度 } if(szStr.cx > nWidth) { nCount--; nLine++; } } else { while(szStr.cx > nWidth && nCount >1) { nCount--; lpStr=sLeft.Left(nCount); GetTextExtentPoint32(hDC, lpStr, nCount, &szStr); } } sDraw+=sLeft.Left(nCount)+_T("\r\n"); //让sDraw等于前nCount个字并在结尾加上\r\n sLeft=sLeft.Right(sLeft.GetLength()-nCount); //让sLeft等于后面的字 nTolLength-=nCount; } uFormat=/*DT_EDITCONTROL|DT_LEFT*/DT_CENTER; DrawText(hDC, sDraw, sDraw.GetLength(), lpRect, uFormat); return nLine; }