Question

VB6 How can I adjust maximum characters in a textbox depending on width of text entered so far?

Asked by: SteveQ2

I need to optimize the maxchars allowed in a VB6 textbox.  It makes a big difference in the maximum number of characters that will fit if the users enter wide letters like "WWW" or narrow letters like "iii".  Since textbox.maxchars can't be changed at runtime, I'm using code in the keypress event to limit the number of characters.  

I found there may be a potential solution using a hidden picturebox to determine the width of text entered so far to determine if more characters should be allowed in the textbox.  But I have not been able to get this work very accurately yet.

intWidthRemaining = Textbox1.Width - PictureboxHidden.TextWidth(Textbox1.text)
intMaxWidthOfPossibleNextChar = PictureboxHidden.TextWidth("W")
If intWidthRemaining > intMaxWidthOfPossibleNextChar Then blnAllowAnotherCharToBeTyped

Can a picturebox be used to determine the width of the text entered so far?  Or, is there an api call that could tell me if a textbox has room for more characters?  

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-04-12 at 06:44:34ID24315691
Topics

VB Controls

,

Visual Basic v1.0.5.x

Participating Experts
4
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Full size Picturebox to Clipboard VB6
    Hi there! Need my program to copy the contents of a picturebox - this means Labels, Textboxes and lines. The full size of the Picturebox is needed! not just what's visible in the window while taking the snapshot. The Picturebox, at it's largest size (twip): Width ~16900 H...
  2. picturebox
    i have a picturebox and a multiline richtextbox. the text in it would get printed in the picturebox. the problem is if the text in the richtextbox automatically word wraps then the text in the picturebox gets printed in a single line. So the text is printed beyond the screen....
  3. Problem Upgrading VB6 Picturebox to .NET
    I am upgrading an VB6 application to .NET. The application uses pictureboxes controls. I need a .NET control that has the following attirbutes: 1. Is a container control 2. Can get the focus 3. Has Keystroke events 4. Has a drawing canvas Is there a control in .NET that w...
  4. How to get a smooth line in Picturebox in vb6
    Hi, I am using vb6. I am drawing a line in picturebox but it is somewhat broken or distorted or can say not smooth. I want to draw a smooth line in the picturebox. Tell me how to get this line. Thanks in Advance
  5. VB6 API
    Hi, Some one gave me a visual basic form (.frm and .frx file) which is an API for printing a Flexgrid. I have used the normal API s like sleep in visual basic. But I don't know how to turn this .frm file to an API and the call it from my vb6 program. Can you help me, ...
  6. Form keypress conflict with CmdButns in VB6
    To display keyboard scan codes, with form_keypreview=true, I display form keypress/up/down values which works fine. If I simply add 2 no-code CmdButns to the form, all keys still display values except the 4 arrow keys, which cause toggling between the 2 CmdButns. Hello?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: chris_bottomleyPosted on 2009-04-12 at 07:48:51ID: 24125844

Hello SteveQ2,

You could select the textbox font to be a fixed rather than proportional font?

Regards,
Chris

 

by: Idle_MindPosted on 2009-04-12 at 07:57:05ID: 24125875

(haven't tried this yet)

Can you change the character limit at run-time with this API?

    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

    Private Const EM_LIMITTEXT = &HC5

    ...
        SendMessage Text1.hwnd, EM_LIMITTEXT, 5, 0&

 

by: SteveQ2Posted on 2009-04-12 at 08:40:11ID: 24126025

Chris_Bottomley,  
I need to keep a proportional font.  The current font setting is Arial 8.  

Idle_Mind,
That API method might be very helpful to reset the character limit but first I need to determine how many characters will fit in the textbox after the user start to type in the textbox.  The number of maxchars or limittext would be very different if the users enter characters like "WWW" or "iii".

 

by: danaseamanPosted on 2009-04-12 at 08:54:10ID: 24126050

You must set PictureboxHidden Font to the same Font as Textbox1, Otherwise PictureboxHidden.TextWidth result will not be accurate.

 

by: HooKooDooKuPosted on 2009-04-13 at 11:55:16ID: 24131951

If you know how to call API functions, the API function GetTextExtentPoint32() can be used to determine the text width.  You should be able to pass the API function the hDC of your TextBox.  The only difficulty is that the return value is likely in pixels, while the dimensions of your TextBox are likely in twips.

 

by: danaseamanPosted on 2009-04-13 at 18:57:05ID: 24134453

Here is API function to return TextWidthA.
Note that TextBox hDc is not exposed so you need to call another API GetDc.
To return as Twips just multiply by Screen.TwipsPerPixelX.

Option Explicit
 
Private Declare Function GetDC Lib "user32.dll" (ByVal hwnd As Long) As Long
Private Declare Function GetTextExtentPoint32 Lib "gdi32.dll" Alias "GetTextExtentPoint32A" (ByVal hdc As Long, ByVal lpsz As String, ByVal cbString As Long, ByRef lpSize As Size) As Long
Private Type Size
   cx As Long
   cy As Long
End Type
 
Private Sub Command1_Click()
   Debug.Print "TextWidthA(Text1)", TextWidthA(Text1)
End Sub
 
Private Function TextWidthA(tb As TextBox) As Long
    Dim sz As Size
    Call GetTextExtentPoint32(GetDC(tb.hwnd), tb.Text, Len(tb.Text), sz)
    TextWidthA = sz.cx * Screen.TwipsPerPixelX
End Function

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

 

by: SteveQ2Posted on 2009-04-14 at 06:54:27ID: 24138181

Danaseaman,

The api calls you have supplied seem like they have alot of potential but they're still giving me very different results if the text I type in is "WWW" or "iiiii".  

I've attached the code I'm running.  It's very similar to the code you supplied but I've added some debugging info to see what it's doing.  Any ideas how I can get it to work as well if the user enters alot of narrow characters as it seems to work if they enter all wide upper case letters?

Option Explicit
' This code requires a new blank form, 1 textbox, and 1 label
Private Declare Function GetDC Lib "user32.dll" (ByVal hwnd As Long) As Long
Private Declare Function GetTextExtentPoint32 Lib "gdi32.dll" Alias "GetTextExtentPoint32A" (ByVal hdc As Long, ByVal lpsz As String, ByVal cbString As Long, ByRef lpSize As Size) As Long
Private intWidthOfTextboxText As Integer
Private intWidthOfWidestPossibleChar As Integer
Private intWidthOfNarrowestPossibleChar As Integer
Private Type Size
   cx As Long
   cy As Long
End Type
Private Sub Form_Load()
   Label1.Width = 6000
   Text1.Text = "W"
   TextWidthA Text1
   intWidthOfWidestPossibleChar = intWidthOfTextboxText
   MsgBox "Widest possible character W: " & intWidthOfWidestPossibleChar
   Text1.Text = "i"
   TextWidthA Text1
   intWidthOfNarrowestPossibleChar = intWidthOfTextboxText
   MsgBox "Narrowest possible character i: " & intWidthOfNarrowestPossibleChar
End Sub
Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)
  TextWidthA Text1
End Sub
Private Function TextWidthA(tb As TextBox) As Long
    Dim sz As Size
    Call GetTextExtentPoint32(GetDC(tb.hwnd), tb.Text, Len(tb.Text), sz)
    intWidthOfTextboxText = sz.cx * Screen.TwipsPerPixelX
    Label1.Caption = "Text width is in ok range: " & intWidthOfTextboxText
    If intWidthOfTextboxText >= Text1.Width Then
       Label1.Caption = "Text exceeds " & Text1.Width & ": " & intWidthOfTextboxText
    End If
 End Function

 

by: HooKooDooKuPosted on 2009-04-14 at 08:00:29ID: 24139012

First, let me make sure I understand what you are trying to do.  
You want to limit the number of characters a user can type into a TextBox.  Your limit is basically the visual size of the TextBox (i.e. you don't want charaters to start strolling).  So basically, if the user types lots of narrow characters, they are allowed to enter more characters into the TextBox than if they use lots of wide characters.  To accomplish this, you are using a Key event to determine if the new character Keyed plus the existing text will fit within the viewable area of the Text Box.

But you are running into a problem, because what you've programmed might work for all WWW but doesn't work for iii, and if you make adjustments for iii, then WWW doesn't work.

First of all, I'd like to suggest that you simply use the KeyPress Event rather than the KeyUp event.  That way, you are only looking at characters that are going to be entered into the textbox rather than looking at every single time a key (like arrow keys) are pressed.  In the new character won't fit, you simply change the character to zero.

As for WWW v. iii, you have to keep in mind that you are only interested in the printable section of the TextBox, not the full size of the TextBox, because the full size of the TextBox includes things like the border of the textbox that is printed.

Listed below is some pseudo-code to demonstrate the idea...

Private Sub Text1_KeyUp( KeyAscii As Integer )
Dim TextBoxWidth as Integer
Dim NewTextWidth as Long
 
  TextBoxWidth = GetClientWidth( Text1.hwnd ) 
  NewTextWidth = GetTextWidth( Text1.hwnd, Text1.Text & Chr( KeyAscii )
  if NewTextWdith > TextBoxWidth then
    KeyAscii = 0
  end if
end sub
 
GetClientWidth( hwnd as long ) as long
  Dim R as RECT
  GetClientRect( hwnd, R )
  GetClientWidth = R.right - R.left
end function
  
GetTextWidth( hwnd as long, Text as String ) as long
  Dim sz as Size
  Call GetTextExtentPoint32( GetDC( hwnd), Text, Len( Text ), sz)
  GetTextWidth = sz.cx * Screen.TwipsPerPixelX
endf function 
 
'Here's the additional API declares needed that you might not already have
Public Type RECT
        Left As Long
        Top As Long
        Right As Long
        Bottom As Long
End Type
Public Declare Function GetClientRect Lib "user32" Alias "GetClientRect" (ByVal hwnd As Long, lpRect As RECT) As Long
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:

Select allOpen in new window

 

by: SteveQ2Posted on 2009-04-14 at 09:16:43ID: 24139862

I can see you understand what I'm trying to accomplish but it doesn't look like GetTextExtentPoint32 is doing it yet.  I can type "WWWWWW" or "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii" before any characters scroll out of sight in a textbox with a width of 1215.  According to GetTextExtentPoint32, the wide letters have a width of 1260 before any characters scroll out of sight.  But GetTextExtentPoint32 says the narrow letters have a width of 2280 before the any characters scroll out of the viewing area of the same textbox.    I really expected to get back a fairly similar number from GetTextExtentPoint32 for WWWWWW" and "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii".  Instead,  what appears to be the same width with more narrow characters is returning nearly double the width measurement from GetTextExtentPoint32 that the fewer wide characters returned. It still looks like it has potential.  Any ideas?

 

by: danaseamanPosted on 2009-04-14 at 09:46:05ID: 24140153

Whatever GetDc is returning appears to not have the corresponding TextBox Font.
Try this code which uses DrawText and the Form hDc.
Note that Form Font has been set to TextBox Font.

Option Explicit
 
Private Declare Function DrawText Lib "user32.dll" Alias "DrawTextA" (ByVal hdc As Long, ByVal lpStr As String, ByVal nCount As Long, ByRef lpRect As RECT, ByVal wFormat As Long) As Long
Private Declare Function GetClientRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
 
Private Type RECT
   Left                 As Long
   Top                  As Long
   Right                As Long
   Bottom               As Long
End Type
 
Private Const DT_CALCRECT As Long = &H400
Private TextBoxClientW  As Long
 
Private Sub Form_Load()
   Dim rct              As RECT
   GetClientRect Text1.hwnd, rct
   TextBoxClientW = (rct.Right - rct.Left)
   Set Me.Font = Text1.Font
End Sub
 
Private Sub Text1_KeyPress(KeyAscii As Integer)
   Debug.Print TextWidthA(Text1, Chr(KeyAscii)), TextBoxClientW
   If KeyAscii > 31 Then
      If TextWidthA(Text1, Chr(KeyAscii)) > TextBoxClientW Then
         KeyAscii = 0
         Debug.Print "Reached limit"
      End If
   End If
End Sub
 
Private Function TextWidthA(tb As TextBox, sChar As String) As Long
   Dim rct              As RECT
   DrawText Me.hdc, tb.Text & sChar, -1, rct, DT_CALCRECT
   TextWidthA = rct.Right - rct.Left
End Function

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:

Select allOpen in new window

 

by: HooKooDooKuPosted on 2009-04-14 at 10:31:36ID: 24140589

I broke down and did some test code, and danaseman seems to be correct.

What did work is when I loaded the DC with a font that matches the font in the TextBox.  The following snippet is UGLY, but it works if you create a new VB6 project, and drop a TextBox and Label on the Form.

From here, you might be able to clean things up and get things working, especially if there is an easier way to load the appropriate font into the DC than to go and create a new font object as the snippet shows.

Private Type Size
        cx As Long
        cy As Long
End Type
 
Private Declare Function SelectObject Lib "gdi32" (ByVal hDC As Long, ByVal hObject As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hDC As Long) As Long
 
Private Declare Function GetTextExtentPoint32 Lib "gdi32.dll" Alias "GetTextExtentPoint32A" (ByVal hDC As Long, ByVal lpsz As String, ByVal cbString As Long, ByRef lpSize As Size) As Long
Private Declare Function GetDC Lib "user32.dll" (ByVal hwnd As Long) As Long
Private Const LF_FACESIZE = 32
Private Const FW_NORMAL = 400
Private Const FW_BOLD = 700
Private Type LOGFONT
        lfHeight As Long
        lfWidth As Long
        lfEscapement As Long
        lfOrientation As Long
        lfWeight As Long
        lfItalic As Byte
        lfUnderline As Byte
        lfStrikeOut As Byte
        lfCharSet As Byte
        lfOutPrecision As Byte
        lfClipPrecision As Byte
        lfQuality As Byte
        lfPitchAndFamily As Byte
        lfFaceName(1 To LF_FACESIZE) As Byte
End Type
Private Declare Function CreateFontIndirect Lib "gdi32" Alias "CreateFontIndirectA" (lpLogFont As LOGFONT) As Long
 
Private Function TextWidthA() As Long
    Dim sz As Size
    Dim hDC As Long
    Dim F As Font
    Dim lf As LOGFONT
    Dim I As Long
    Dim hFont As Long
    Dim hOldFont As Long
    
    Set F = Text1.Font
    lf.lfWeight = IIf(F.Bold, FW_BOLD, FW_NORMAL)
    lf.lfCharSet = F.Charset
    lf.lfItalic = F.Italic
    For I = 1 To Len(F.Name)
        lf.lfFaceName(I) = Asc(Mid$(F.Name, I, 1))
    Next I
    lf.lfFaceName(I) = 0
    lf.lfHeight = F.Size
    lf.lfStrikeOut = F.Strikethrough
    lf.lfUnderline = F.Underline
    lf.lfWeight = F.Weight
    
    hFont = CreateFontIndirect(lf)
    
    hDC = GetDC(Text1.hwnd)
    hOldFont = SelectObject(hDC, hFont)
    
    Call GetTextExtentPoint32(hDC, Text1.Text, Len(Text1.Text), sz)
    TextWidthA = sz.cx * Screen.TwipsPerPixelX
 
    Call SelectObject(hDC, hOldFont)
    Call DeleteObject(hFont)
    Call ReleaseDC(Text1.hwnd, hDC)
 
End Function
 
Private Sub Text1_Change()
    Label1.Caption = CStr(TextWidthA)
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:

Select allOpen in new window

 

by: SteveQ2Posted on 2009-04-19 at 10:21:22ID: 31569321

Danaseaman(Guru), thank you!  I am so impressed!  I had tried and tried but could not get this problem solved.  It was beginning to seem like it might be impossible.  Thank you!  

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...