eMbedded Visual C++ 4.0eMbedded Visual C++ 3.0Pocket PC 2002eVCWindows Mobile中级开发Visual StudioWindowsC++
在 Pocket PC 上实现 DT_END_ELLIPSIS 标志






3.67/5 (4投票s)
扩展 DrawText 函数以显示带有终止省略号的截断文本
引言
众所周知,Windows CE API 提供的 DrawText
函数不支持 DT_END_ELLIPSIS
标志。这使得模拟列表视图控件在报告模式下的行为变得更加困难:不适合列宽的文本单元格将以终止省略号(...)显示。
有一种方法可以解决这个问题,请参见 此处,但它是基于 MFC 的,而我想要一个仅使用 API 的版本。
本文通过实现 DrawTextEx
函数,提供了一个非常简单的解决方案。
解决方案
这里提供的解决方案简单明了,并试图保留桌面版 DrawText
的精神:提供的字符串必须允许就地修改。
为了确保开发人员理解这一点(该函数会移除 char 指针的 const 性质),必须提供一个额外的标志:DT_MODIFYSTRING
。否则,该函数不会对字符串进行就地修改,也不会显示省略号。
在确定用户真正理解这些问题后,该函数可以通过计算字符串长度(如果未提供)以及其屏幕大小来开始工作。
如果字符串的屏幕大小大于提供的矩形(在本例中为宽度),则需要将其分割并在其末尾添加一个 Unicode 省略号字符。请注意,该函数尝试估计省略号字符将放置的位置,以避免进入漫长而繁琐的试错循环。只有当第一次大小估计大于矩形的宽度时,才会最终进入此循环。
最后,当带有附加省略号字符的截断字符串适合指定的矩形时,我们可以使用经典的 DrawText
函数显示它。
代码
如您所见,代码非常易于理解。您可以立即使用它,或者根据需要进行更改(肯定有很多可以更改的地方!)。
// // The UNICODE ellipsis character // #define ELLIPSIS ((TCHAR)0x2026) // DrawTextEx // // Extended version of DrawText // int DrawTextEx(HDC hDC, LPCTSTR lpString, int nCount, LPRECT lpRect, UINT uFormat) { // // Check if the user wants to use the end ellipsis style // if(uFormat & (DT_END_ELLIPSIS | DT_MODIFYSTRING)) { SIZE szStr; LPTSTR lpStr = (LPTSTR)lpString; // Make it non-const int nWidth = lpRect->right - lpRect->left; // Rect width // // If the user did not specify a string length, // calculate it now. // if(nCount == -1) nCount = _tcslen(lpStr); // // Check if the text extent is larger than the rect's width // GetTextExtentPoint32(hDC, lpStr, nCount, &szStr); if(szStr.cx > nWidth) { // // Make a worst-case assumption on the char count // int nEstimate = (nCount * nWidth) / szStr.cx + 1; if(nEstimate < nCount) nCount = nEstimate; // // Insert the initial ellipsis, by replacing the last char // lpStr[nCount-1] = ELLIPSIS; GetTextExtentPoint32(hDC, lpStr, nCount, &szStr); // // While the extents are larger than the width, remove one // character at the time // while(szStr.cx > nWidth && nCount > 1) { lpStr[--nCount] = 0; // Remove last lpStr[nCount-1] = ELLIPSIS; // Replace last with ... GetTextExtentPoint32(hDC, lpStr, nCount, &szStr); } } // // Remove the formatting options, just in case // uFormat &= ~(DT_END_ELLIPSIS | DT_MODIFYSTRING); } return DrawText(hDC, lpString, nCount, lpRect, uFormat); }