Search code examples
vb6

Proper Casing in VB6


I am doing a quiz game in VB6. I need the textbox to automatically capialize the first letter but this code

Private Sub Anstxt_Change()
Anstxt.Text = StrConv(Anstxt.Text, vbProperCase)
End Sub

causes the word to invert. So instead of "Trees" it turns into "Seert"

How do I change this?


Solution

  • Pay attention to where the cursor is positioned in the textbox when the event Change occurs: its at the start of the textbox. Add a Debug.Print statement to see what's going on while you type:

    Private Sub Anstxt_Change()
       Debug.Print StrConv(Anstxt.Text, vbProperCase)
       Anstxt.Text = StrConv(Anstxt.Text, vbProperCase)
    End Sub
    

    The output looks like

    T
    T
    Rt
    Rt
    Ert
    Ert
    Eert
    Eert
    Seert
    Seert
    

    Two things to notice here: the Change event is triggered twice: once from typing and once from changing the value of the textbox within the Change event. That gives you an idea that manipulating the text of a textbox in its Change event isn't a good idea. I suggest to put this code in the LostFocus event instead.

    The second thing to notice is that as the cursor is always at the start of the textbox, the letters you type are inserted there in front of the existing letters. So after you change the .Text property of the textbox, you should position the cursor at the end of the textbox with the .SelStart method:

    Anstxt.SelStart = Len(Anstxt.Text)
    

    e.g.

    Private Sub Anstxt_Change()
       Anstxt.Text = StrConv(Anstxt.Text, vbProperCase)
       Anstxt.SelStart = Len(Anstxt.Text)
    End Sub