文本框和下拉列表框等,都有一个限制输入字符数的属性 Object.MaxLength,
值得注意的是,它限制的是字符数,而并非字节数,
在中英文混合输入的时候,要限制字节数,就可以看到他的不足了
(PS:一个中文字符=两个字节)
所以我写了一下一个过程:用来判断输入字节数是否超标,如果超过,就修正
用法:
如果是多窗口程序,请将代码放在一个模块上
一般在 Object_TextChanged 中引用该过程
示例:
ChkTxtMaxByte(spBlogCmtText, 1000)
限制名为spBlogCmtText的文本框的最大字节为1000

'检验文本框输入的字节数是不是大于设定
‘By Null  2006-10-04
    Public Sub ChkTxtMaxByte(ByVal sender As Object, ByVal MaxByte As Integer)
        If System.Text.Encoding.Default.GetBytes(sender.Text).Length > MaxByte Then
            Dim n As Integer
            Dim StrByteLen As Integer
            MsgBox("输入的字符串字节数大于最大值:" & MaxByte)
            For n = Int(MaxByte / 2) To MaxByte
                StrByteLen = System.Text.Encoding.Default.GetBytes(Strings.Left(sender.Text, n)).Length
               
                If StrByteLen = MaxByte Then
                    sender.Text = Strings.Left(sender.Text, n)
                    Exit Sub
                End If

                If StrByteLen > MaxByte Then
                    sender.Text = Strings.Left(sender.Text, n - 1)
                    Exit Sub
                End If
            Next
        End If
    End Sub
http://hi.baidu.com/hetaoos/blog/item/29dffe1f4e2f5b63f624e4a4.html
posted on 2007-01-05 12:45  mbskys  阅读(471)  评论(0)    收藏  举报