views:

351

answers:

4

How do you determine the length of a string of text in Arial Bold font, and then center it in VB6?

If not here, can you point me in a direction where I might be able to find this information?

We're not using a "label" or "picture box" do print the text to the screen. We are sizing the text on the fly, and allowing the user to scale the size of our application to their liking. We write the text to screen using code.

+1  A: 

I can't remember the specifics (it's been about 3 years since I last used VB 6), but there's a method on Form called something like "MeasureString". It takes the string, and measures it according to the font settings of the form.

Also, here's a comment posted by Jason Lepack in case I've misunderstood and over-complicated your requirements:

"Labels usually have an alignment property. If you set it to align to center then, regardless of the font face it should center in the label".

Neil Barnwell
Yeah, I wasn't brave enough to venture the downvotes for my "answer" ;)
Jason Lepack
A: 

There are Win32 GDI functions you can invoke: see for example GetTextExtentPoint32 at http://msdn.microsoft.com/en-us/library/ms534223(VS.85).aspx

ChrisW
+5  A: 

One way is to have a hidden picture box and setup the font specs of that picture box the way you want.

Then use the TextHeight and TextWidth methods of the PictureBox to take your measurements. The Units will be in whatever scalemode the Picture Box is set to.

If you are printing directly to the printer or form then just set your font FIRST then take your measurements.

To center it

MyText = "Hello World"
<displayarea>.FontName = "Arial"
<displayarea>.FontSize = 14
<displayarea>.FontBold = True
TextWidth = <displayarea>.TextWidth(MyText)
TextLeftCoordinate = <displayarea>.ScaleLeft+<displayarea>.ScaleWidth/2-TextWidth/2
<displayarea>.CurrentX = TextLeftCoordinate
<displayarea>.Print MyText

Substitute displayarea with whatever object you are using.

Based on your updated answer note that the hidden picture box suggestion isn't used to print. It is only get text measurement. However you are printing directly to the form so you just need to use the code example above.

RS Conley
+1 A very nice solution, without resorting to API calls.
JeffK
A: 

Your best option may be Form.TextWidth, which appears to return the width of a string in twips. I've just taken this approach in order to dynamically size a button based on the length of the label that needs to appear inside it.

There is also a corresponding function called Form.TextHeight which would allow you to do the same thing in the vertical dimension.

Make sure that you set the Font property of the form to match the Font property of the control you're intending to measure the text for, otherwise you'll get incorrect results.

Read more at http://msdn.microsoft.com/en-us/library/aa267168(VS.60).aspx