| A bug in the
intrinsic TextBox control does not allow the value of the KeyAscii parameter to be changed
in the event. One way to work around this is to scan the text in the change event and
convert the text to what you want.
If you just want to modify the case of the text, it's not much of a problem. If you want
to "cancel" the key press (in VB you would set KeyAscii = 0) there may be a bit
of a flash when you modify the text, but it's the best you can do.
First you will need a variable that as a
scope level of the form or project. Place the following code in the Declarations section
of the form or standard module.
Dim TextChanging
This variable is our flag to indicate to
ourselves when we are changing the text after a change or when the change is being fired
by the textbox input. If we were not to set and check this flag, when a character was
entered and the change event fired, if we were to change the text again (to uppercase for
example) the change event would fire again when we reassigned the text. Depending on what
you were doing, you could get stuck in a loop.
Next, the code is placed in the TextBox
Change event. Below, we are forcing the text in the Text1 control to stay uppercase, and
the text in Text2 is forced to always be lowercase, and Text3 does not allow spaces to be
entered.
Private Sub Text1_Change()
'Force All Text to UpperCase
On Error Resume Next
Dim Curpos
If TextChanging Then Exit Sub
TextChanging = True
Curpos = Text1.SelStart
Text1.Text = UCase(Text1.Text)
Text1.SelStart = Curpos
TextChanging = False
End Sub
Private Sub Text2_Change()
'Force All Text to LowerCase
On Error Resume Next
Dim Curpos
If TextChanging Then Exit Sub
TextChanging = True
Curpos = Text2.SelStart
Text2.Text = LCase(Text2.Text)
Text2.SelStart = Curpos
TextChanging = False
End Sub
Private Sub Text3_Change()
'Don't Allow Spaces
On Error Resume Next
Dim Curpos
If TextChanging Then Exit Sub
TextChanging = True
Curpos = Text3.SelStart
Text3.Text = Replace(Text3.Text, " ",
"")
If Curpos > Len(Text3.Text)
Then
Text3.SelStart
= Len(Text3.Text)
Else
Text3.SelStart
= Curpos
End If
TextChanging = False
End Sub |