如果要写一个通用的处理方式,建议使用TEXT的TAG属性来标记。比如说定义如下:TAG=1只允许输入汉字;TAG=2只允许输入字母;TAG=3只允许输入数字,其余不作限制。
则一个通用的处理代码如下:
Private Sub txtField_KeyPress(KeyAscii As Integer)
KeyAscii = funCheckInput(KeyAscii ,txtfield.tag)
End Sub
public function funCheckInput(keyAscii as integer,Tag as string)as integer
begin
select case tag
case "1":'是否汉字的检查
case "2":'.......
case else:
funCheckInput=keyAscii
end select
end function
在TEXT的ONKEYPRESS事件里写:
-----检查输入长度-----
Private Sub txtField_KeyPress(Index As Integer, KeyAscii As Integer)
'如果当前输入键为删除键或者当前选中内容长度大于1就不予检查
If KeyAscii = vbKeyBack Or txtField(Index).SelLength > 0 Then Exit Sub
'计算输入字符串的真实长度
n = realLength(txtField(Index).Text & Chr(KeyAscii))
'如果输入字符串的真实长度大于最大长度
If n > txtField(Index).MaxLength Then
'则鸣笛报警,并禁止输入
Beep
KeyAscii = 0
End If
End Sub
'求字符串显示长度(汉字占两位)
Public Function realLength(str As String) As Long
realLength = LenB(StrConv(str, vbFromUnicode))
End Function
-------------结束------------
你可以根据以上的代码自己写出控制输入框只能输入字母或者数字或者汉字的程序。
比如:只允许输入汉字的:
Private Sub txtField_KeyPress(KeyAscii As Integer)
'如果当前输入键为删除键或者当前选中内容长度大于1就不予检查
If KeyAscii = vbKeyBack Or txtField.SelLength > 0 Then Exit Sub
'
n = realLength(txtField.Text & Chr(KeyAscii))
'如果输入字符串的真实长度不等于len函数计算出来的长度的两倍,说明里面有非汉字
If n <>2* len((txtField.Text & Chr(KeyAscii)) Then
'则鸣笛报警,并禁止输入
Beep
KeyAscii = 0
End If
End Sub
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Const GWL_STYLE = (-16)
Const ES_NUMBER = &H2000&
Public Sub SetNumber(NumberText As TextBox, Flag As Boolean)
Dim curstyle As Long, newstyle As Long
If Flag Then
curstyle = curstyle Or ES_NUMBER
Else
curstyle = curstyle And (Not ES_NUMBER)
End If
''curstyle = WS_POPUP 这句话不要
newstyle = SetWindowLong(NumberText.hwnd, GWL_STYLE, curstyle)
NumberText.Refresh
End Sub
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Const GWL_STYLE = (-16)
Const ES_NUMBER = &H2000&
Public Sub SetNumber(NumberText As TextBox, Flag As Boolean)
Dim curstyle As Long, newstyle As Long
If Flag Then
curstyle = curstyle Or ES_NUMBER
Else
curstyle = curstyle And (Not ES_NUMBER)
End If
curstyle = WS_POPUP
newstyle = SetWindowLong(NumberText.hwnd, GWL_STYLE, curstyle)
NumberText.Refresh
End Sub