keypress、keydown、keyup事件无法捕捉“粘贴”动作,比如ctrl-v粘贴,也无法捕捉delete键,用change事件:
Private Sub Text1_Change()
Do While Me.TextWidth(Text1) > Me.TextWidth(Space(12))
Text1 = Left(Text1, Len(Text1) - 1)
Loop
Text1.SelStart = Len(Text1)
End Sub
此操作须限制:text1的字体、字号与窗体的字体、字号一致,如果没有特别必要,一般情况下两者是一致的。
在keypress事件中进行判断
Private Sub Text1_KeyPress(KeyAscii As Integer)
tstr = StrConv(Text1, vbFromUnicode)
If Len(tstr) >= 6 And KeyAscii <> vbKeyBack And KeyAscii <> vbKeyDelete Then
KeyAscii = 0
End If
End Sub
text中有个属性是maxchar或者maxpass类似的属性,设置一个数字就行了,具体我也忘了,平时很少用VB,