Page 1 of 1

GetTextWidth bug when string contains "&"

Posted: Wed Dec 07, 2005 1:17 pm
by mindplay
For strings containing an ampersand (the "&" character), the GetTextWidth function returns a size that is too small - as you can see in the following simple ASP example, this is true.

Code: Select all

<%

Const AX_GIF = 2
Const AX_To8Colors = 8
Const AX_NoDither = 0
Const AX_ToColors = 0

BG = RGB(255,255,255)
FG = RGB(255,0,0)
Text = "High & Low"

Set Pic = Server.CreateObject("GflAx.GflAx")
Pic.EnableLZW = True

Pic.FontName = "Verdana"
Pic.FontSize = 36

W = Pic.GetTextWidth(Text)
H = Pic.GetTextHeight(Text)

Pic.NewBitmap W, H, BG
Pic.TextOut Text, 0, 0, FG

Pic.SaveFormat = AX_GIF
Pic.ChangeColorDepth AX_To8Colors, AX_NoDither, AX_ToColors
Pic.SaveBitmap Server.MapPath("test.gif")

%>
<HTML><HEAD></HEAD><BODY BGCOLOR=#000000><IMG SRC="test.gif"></BODY></HTML>
It happens because the "&" character in the windows API subroutine interprets "&" as meaning "underline the next character", which is used to display keyboard shortcuts in menus and dialogs.

To work around this problem, simply replace "&" with "&&" in your string when getting the text width, e.g.:

W = Pic.GetTextWidth(Replace(Text,"&","&&"))

The "&&" combination is interpreted by the windows subroutine as "an actual & character", and will give the correct resulting width.

Re: GetTextWidth bug when string contains "&"

Posted: Wed Dec 07, 2005 8:20 pm
by xnview
mindplay wrote:For strings containing an ampersand (the "&" character), the GetTextWidth function returns a size that is too small - as you can see in the following simple ASP example, this is true.

It happens because the "&" character in the windows API subroutine interprets "&" as meaning "underline the next character", which is used to display keyboard shortcuts in menus and dialogs.

To work around this problem, simply replace "&" with "&&" in your string when getting the text width, e.g.:

W = Pic.GetTextWidth(Replace(Text,"&","&&"))

The "&&" combination is interpreted by the windows subroutine as "an actual & character", and will give the correct resulting width.
Ok, i'll fix it