How can we calculate the width of the control from the length of a string
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.
Re: How can we calculate the width of the control from the length of a string
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
[email protected]
The best way to escape a problem, is to solve it.
Re: How can we calculate the width of the control from the length of a string
If you set the label's Autosize = True then the label will automatically expand with the length of the caption.
Re: How can we calculate the width of the control from the length of a string
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.
Re: How can we calculate the width of the control from the length of a string
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.
Re: How can we calculate the width of the control from the length of a string
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