R – Centering fonts in VB6

fontsstringvb6

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

We are not using a "label" or "picture box" to 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.

Best Answer

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.

Related Topic