The
GetCharABCWidths API function for TrueType fonts, and the
GetCharWidth for other fonts, allow to calculate the width of characters in logical units.
The following is a sample code featuring the
GetCharABCWidths function:
FUNCTION GetTextWidth(hDC, cText)
DECLARE INTEGER GetCharABCWidths IN gdi32;
INTEGER hdc, INTEGER uFirstChar,;
INTEGER uLastChar, STRING @lpabc
LOCAL ii, ch, nResult, cBuffer, nLen
nResult = 0
cBuffer = Repli(Chr(0), 12)
FOR ii=1 To Len(cText)
ch = Asc(SUBSTR(cText, ii,1))
= GetCharABCWidths(hDC, m.ch, m.ch, @cBuffer)
nLen = buf2dword(SUBSTR(cBuffer, 1,4)) +;
buf2dword(SUBSTR(cBuffer, 5,4)) +;
buf2dword(SUBSTR(cBuffer, 9,4))
nResult = nResult + nLen
ENDFOR
RETURN nResult
FUNCTION buf2dword(lcBuffer)
RETURN Asc(SUBSTR(lcBuffer, 1,1)) + ;
BitLShift(Asc(SUBSTR(lcBuffer, 2,1)), 8) +;
BitLShift(Asc(SUBSTR(lcBuffer, 3,1)), 16) +;
BitLShift(Asc(SUBSTR(lcBuffer, 4,1)), 24)
The problem with this code is that a TextBox control in FoxPro is not linked to a device context, at least you can not reach that device context if it ever exists.
There is a solution, rather bulky, -- creating a virtual device context, selecting into it a font that is used in the TextBox, and then calling the GetTextWidth function. All in all it's going to be 50..100 lines of code. Myself, I found that
GetCharABCWidths gets quite accurate results for TrueType fonts.
* * *
The
GetTextMetrics function returns average dimensions for characters in
TEXTMETRIC structure. Certainly you can not predict a content of a TextBox. So may be this function is more suitable for you.
* * *
FoxPro code samples:
Reading metrics for the currently selected fonthttp://www.news2news.com/vfp/?example=339&function=522Vertical Label control (members area)
http://www.news2news.com/vfp/?example=398&function=522