VB中的Text控件怎么才能让用户只能输入数字而不能输入其他的呢?

2024-11-04 20:45:42
推荐回答(3个)
回答(1):

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
Private Const GWL_STYLE = (-16)
Private Const ES_NUMBER As Long = &H2000&

Private Sub Form_Load()
Dim style As Long
Text1.Text = ""
style = GetWindowLong(Text1.hwnd, GWL_STYLE)
SetWindowLong Text1.hwnd, GWL_STYLE, style Or ES_NUMBER
End Sub

用API好处是,输入的不是数字时,会自动提示。

回答(2):

Private Sub Text1_Change()
If IsNumeric(Text1.Text) = False Then
MsgBox "文本框输入了非法字符!", 16, "错误!"
Text1.Text = ""
Text1.SetFocus
End If
End Sub

回答(3):

请问使用的是VB6吗?参考以下代码:
Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii < 48 Or KeyAscii > 57 Then
KeyAscii = 0
End If
End Sub

数字正数