textbox.maxlength可以限定输入内容的长度,但是如果想更精细地实现限定ansi字符串的长度该如何实现呢?
ansi编码下,中文占2字节,英文1字节,textbox.maxlength无法限定混有中英文的ansi字符串。
考虑一般情况下限定输入长度的方法:
1.maxlength
2.在KeyPress事件中处理
3.在TextChanged中处理
Dim oldTxt = ""
Private Sub txtSingleTxt_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtSingleTxt.TextChanged
Dim c = SMS.Global.MaxLen - SMS.Global.TxtLen(txtSingleTxt.Text)
lbCount3.Text = c
If (c < 0) Then
txtSingleTxt.Text = oldTxt
Else
oldTxt = txtSingleTxt.Text
End If
End Sub
Private Sub tbParentsMsg_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tbParentsMsg.KeyPress
Dim c = SMS.Global.MaxLen - SMS.Global.TxtLen(tbParentsMsg.Text)
lbCount3.Text = c
If (c <= 0 And (vbBack <> e.KeyChar)) Then
e.Handled = True
End If
End Sub