views:

101

answers:

1

In a Win32 GUI application I need to determine the width of area occupied by a string on a toolbar button so that I adjust the button width accordingly. The toolbar is plain old ToolbarWindow32 windows class. I use the following code:

 HDC dc = GetDC( toolbarWindowHandle );
 SIZE size;
 GetTextExtentPoint32( dc, stringToMeasure, tcslen(stringToMeasure), &size );

For some fixed string (say "Hello") size.cx is filled with say 72 but when I make a screenshot of the toolbar with the very same string displayed on a button I see that the string occupies say 56 pixels.

The difference clearly depends on system fonts settings. I use "large fonts" and the value obtained by code is bigger than what is occupied on screen. On machines with "small fonts" the value obtained is smaller.

I thought if I use GetTextExtentPoint32() on a window device context it will return exactly the right size. What am I doing wrong?

+3  A: 

The font used by the toolbar won't be selected into the DC so you'll need to work out what font it is using, create a copy, select it into the DC, get the size and then select the font out (else you could end up with a resource leak). You will currently be getting the size of the system font I expect, or whatever the default DC font is.

You could try finding the font handle used by sending a WM_GETFONT message to the toolbar window but this isn't guaranteed to return the actual font used when the text is displayed. It all depends on how the toolbar works internally.

However I'm pretty sure that the Win32 toolbar uses the menu font for rendering button text, which can be discovered using a combination of SystemParametersInfo and the NONCLIENTMETRICS structure.

If I was at work I'd post some code.

Don't you just love Win32?

BTW, I use the toolbar button text feature and have never had to size the button by hand in this way.

http://msdn.microsoft.com/en-us/library/ms724947%28VS.85%29.aspx http://msdn.microsoft.com/en-us/library/ms724506%28VS.85%29.asp

Rob
Turns out, sending WM_GETFONT obtains exactly the necessary font.
sharptooth