可以用以下的Windows API:
1.
BOOL GetTextExtentPoint32(
HDC hdc, // handle to device context, 如Canvas.Handle
LPCTSTR lpString, // pointer to text string, 如PChar( str )
int cbString, // number of characters in string, 如Length( str )
LPSIZE lpSize // pointer to structure for string size
);
该函数是用来获得一字符串的长度,但不能计算包含有TAB符的字符串的长度。
2.
BOOL GetTextExtentExPoint(
HDC hdc, // handle to device context
LPCTSTR lpszStr, // pointer to character string
int cchString, // number of characters in string
int nMaxExtent, // maximum width for formatted string
LPINT lpnFit, // pointer to value specifying max. number of
// chars.
LPINT alpDx, // pointer to array for partial string widths
LPSIZE lpSize // pointer to structure with string dimensions
);
此函数比上一个函数的好处是它可以计算在nMaxExtent宽度内可以容纳的字符的个数,并且可以返回每一个字符的宽度。不过它还是不能正确计算包含有TAB符的字符串的长度。
3.
int DrawText(
HDC hDC, // handle to device context
LPCTSTR lpString, // pointer to string to draw
int nCount, // string length, in characters
LPRECT lpRect, // pointer to struct with formatting dimensions
UINT uFormat // text-drawing flags
);
此函数uFormat参数中有DT_CALCRECT标志,则可以进行计算字符串的显示区域(长和宽)。注意:如只要计算字符串的宽度,就要包含DT_SINGLELINE标志。它也不能正确计算包含有TAB符的字符串的长度。
4.
int DrawTextEx(
HDC hdc, // handle to device context
LPTSTR lpchText, // pointer to string to draw
int cchText, // length of string to draw
LPRECT lprc, // pointer to rectangle coordinates
UINT dwDTFormat, // formatting options
LPDRAWTEXTPARAMS lpDTParams // pointer to struct with options
);
此函数是上一个函数的扩展,它可以计算包含有TAB字符的字符串的正确宽度。