Click to See Complete Forum and Search --> : How can we calculate the width of the control from the length of a string


Ali Habib
April 12th, 2001, 05:24 AM
How can we calculate the width of the control from the length of a string. I can get the length of a string using len(strvar), now I need to reset the width of the control (label or command button) so that the strvar is completely displayed as the caption of the control.

thanks

Ali.

Cakkie
April 12th, 2001, 05:42 AM
I made a quick example, wich uses the printer object (yes, the printer object)

' create a form, add a textbox and a commandbutton
private Sub Text1_Change()

Dim W as Single
Dim oldFont as Variant

' get printer settings
set oldFont = Printer.Font

' set font to the font of the control you want to resize
set Printer.Font = Command1.Font

' het width of text
W = Printer.TextWidth(Text1.Text)

' set width and caption
Command1.Width = W + 360
Command1.Caption = Text1.Text

' restore original font to printer
set Printer.Font = oldFont

End Sub



When you type something in the textbox, you will see that the button automatically resizes

Tom Cannaerts
slisse@planetinternet.be

The best way to escape a problem, is to solve it.

Cubbie
April 12th, 2001, 06:11 AM
If you set the label's Autosize = True then the label will automatically expand with the length of the caption.

Cimperiali
April 12th, 2001, 06:14 AM
If it is a label. If not?
I enjoied cakkie solution.
I used to use an Api to get the width of default fonts (=the font of form), but it did not work properly...


Special thanks to Lothar "the Great" Haensler. Come back soon, you Guru.

javalar
April 12th, 2001, 07:35 AM
The Form object also has a "TextWidth" method. It may be more correct to use that, because if the computer your application is running on does not have a printer installed, the code will crash! Simply substitute the "Printer" object for the name of your form (or the "Me" keyword).

You may also have unexpected behaviour if the default printer is a text-only printer.

One last thing: don't forget to restore the "Font" property of the form to its original value or you could have some strange behaviour with labels.

shree
April 12th, 2001, 08:58 AM
If it's not a label, still you can use a dummy label on your form to compute the height and width of the string.

lbldummy.Font = ....
...
lblDummy.AutoSize = True
lblDummy.Caption = yourString

text1.width = lblDummy.width + Some_margin
text1.height = lblDummy.height + Some_margin