This works but has the side effect of moving the insertion point to the beginning of the textbox on the eleventh character for reasons that I don't understand.
The length is tested at nine as the KeyPress event occurs before "key" is added to the string and there seems to be no way of preventing it being added.
B4X:
Sub TextBox1_KeyPress (key)
If StrLength(Textbox1.Text) >=9 Then
Textbox1.Text= SubString(Textbox1.Text,0,9)
End If
End Sub
An improvement on my first method. I still don't understand why the insertion point moves but this code resets it. One advantage of this method is that if the user pastes in a string longer than the required length then if he tries to edit it the string is truncated which would not happen with the "ignorekey" method.
B4X:
Sub TextBox1_KeyPress (key)
If StrLength( textbox1.Text) >=9 Then
If Asc(key)>31 Then
Textbox1.Text= SubString(Textbox1.Text,0,9)
Textbox1.SelectionStart = 9
End If
End If
End Sub
EDIT: The following is even better for user editing as the insertion point doesn't do unexpected things
B4X:
Sub TextBox1_KeyPress (key)
If StrLength( textbox1.Text) >=9 Then
If Asc(key)>31 Then
ss = Textbox1.SelectionStart
Textbox1.Text= SubString(Textbox1.Text,0,9)
Textbox1.SelectionStart = ss
End If
End If
End Sub
EDIT AGAIN!: I forgot that B4PPC 5.50 can now evaluate more complex logical conditions so the following is a little more elegant!
B4X:
Sub TextBox1_KeyPress (key)
If StrLength(textbox1.Text) >=9 AND Asc(key) > 31 Then
s = textbox1.SelectionStart
Textbox1.Text= SubString(Textbox1.Text,0,9)
textbox1.SelectionStart = s
End If
End Sub