我想制作一个文本框控件,只能接受数字值。
在VB6中,我该怎么做?
右键点击控制框 > 组件 > 控件 -> 微软掩码编辑控件 6.0。
或者使用普通文本框:
Private Sub Text1_Validate(Cancel As Boolean)
Cancel = Not IsNumeric(Text1.Text)
End Sub
Dim textval As String
Dim numval As String
Private Sub TextBox1_Change()
textval = TextBox1.Text
If IsNumeric(textval) Then
numval = textval
Else
TextBox1.Text = CStr(numval)
End If
End Sub
Private Sub text1_KeyPress(KeyAscii As Integer)
If Not IsNumeric(text1.Text & Chr(KeyAscii)) And Not KeyAscii = 8 Then KeyAscii = 0
End Sub
我让API为我完成它。我将这个函数添加到.bas模块中,并为需要设置为数字的任何编辑控件调用它。
Option Explicit
Private Const ES_NUMBER = &H2000&
Private Const GWL_STYLE = (-16)
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
'set an editbox to numeric only - return the previous
'style on success or zero on error
Public Function ForceNumeric(ByVal EditControlhWnd As Long) As Long
Dim lngCurStyle As Long
Dim lngReturn As Long
lngCurStyle = GetWindowLong(EditControlhWnd, GWL_STYLE)
If lngCurStyle <> 0 Then
lngReturn = SetWindowLong(EditControlhWnd, GWL_STYLE, lngCurStyle Or ES_NUMBER)
End If
ForceNumeric = lngReturn
End Function
要使用它,请使用文本框的句柄调用该函数。
Private Sub Form_Load()
Dim lngResult As Long
lngResult = ForceNumeric(Text1.hwnd)
End Sub
我通常使用这段代码:
Private Sub text1_KeyPress(KeyAscii As Integer)
If Not IsNumeric(Chr(KeyAscii)) And Not KeyAscii = 8 Then
KeyAscii = 0
End If
End Sub
Private Sub txtReceiptID_KeyPress(KeyAscii As Integer)
Dim Keychar As String
If KeyAscii > 31 Then
Keychar = Chr(KeyAscii)
If Not IsNumeric(Keychar) Then
KeyAscii = 0
End If
End If
End Sub
以下内容可用于整数:
Private Sub text1_KeyPress(KeyAscii As Integer)
If Not IsNumeric(text1.Text & Chr(KeyAscii)) And Not KeyAscii = 8 Then KeyAscii = 0
if (KeyAscii>=43) and (KeyAscii<=46) Then KeyAscii = 0
'it ignores '-', '+', '.' and ','
End Sub
Private Sub txtControl_KeyPress(KeyAscii As Integer)
KeyAscii = RealKeyascii(txtControl, KeyAscii, 256 ^ 8)
End Sub
只需编写简单的1行代码 在文本中更改 Text1.text1=val(text1.text)