使用Textbox的KeyPress事件。
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar.ToString = Keys.Back.ToString Then
e.Handled = False
End If
If TextBox1.Text.Length > 5 Then
e.Handled = True
//此句解决了输入超过五个字后弹框一直出现,按退格弹框也一直出现的bug
TextBox1.Text = TextBox1.Text.Substring(0, 4)
MessageBox.Show("不能超过五个字")
End If
End Sub