2

I wanna make only predefined characters to be able to used on my textbox in vb6. How can i achive that?

Predefined characters will be like 0-9 and A, C, M, E all other characters besides these gonna give a msgbox as err. it can also be a,c,m,e i can use Ucase() to solve it.

JimmyPena
  • 8,694
  • 6
  • 43
  • 64
Berker Yüceer
  • 7,026
  • 18
  • 68
  • 102

3 Answers3

7

You can;

private Sub atextbox_KeyPress(keyascii As Integer)
   if InStr(1, "0123456789ACME", Chr$(keyascii)) = 0 Then keyascii  = 0 '//case sensitive
End Sub

or

if Chr$(keyascii) like "[0-9]" or Chr$(keyascii) like "[ACMEacme]"

alternatively formatted

select case true
    case chr$(keyascii) like "[0-9]"
    case chr$(keyascii) like "[ACMEacme]"
    case else
        keyascii = 0
end select
Alex K.
  • 171,639
  • 30
  • 264
  • 288
5

You can detect each character entered using the KeyPress event and checking the ASCII value. If you set it to 0, the press will be ignored. Be sure to also check in the Change event to catch pasting, etc.

Also, don't use a messagebox as this will annoy users.

Deanna
  • 23,876
  • 7
  • 71
  • 156
  • thats the idea! annoying users that does it wrong while i told them not to use other than defined characters.. xD – Berker Yüceer Dec 12 '11 at 14:25
  • 1
    Well spotted about pasting, etc. I'd be inclined to put the check in the Change event only, for that reason. – Brian Hooper Dec 12 '11 at 14:33
  • Only problem with Change only is if they type an out of range character and it's removed, it forces the carat back to the beginning. (My code does this at the moment which winds my colleagues up :) – Deanna Dec 12 '11 at 14:53
2

Use the KeyPress event:

Private Sub txtBox_KeyPress(KeyAscii As Integer)
    Dim KeyChar As String
    If KeyAscii > 31 Then 'ignore low-ASCII characters like BACKSPACE
        KeyChar = Chr(KeyAscii)

        If Not IsAllowed(KeyChar) Then
          KeyAscii = 0
          MsgBox.Show("The allowed characters are ... ")
        End If
    End If
End Sub

The IsAllowed function will contain the allowed key codes.

stuartd
  • 70,509
  • 14
  • 132
  • 163
  • Using IsNumeric and keeping the allowed character values in an array of Integers should keep it concise. – stuartd Dec 12 '11 at 14:28