回答:可以用正则表达式来处理,也可以这样:
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim strNumbers As String
strNumbers = "1234567890" + Chr(8) + Chr(46)
If InStr(strNumbers, Chr(KeyAscii)) = 0 Then
KeyAscii = 0
End If
End Sub
Declare Function SetWindowsHookEx Lib "user32" Alias _
"SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, _
ByVal hmod As Long, ByVal dwThreadId As Long) As Long
Declare Function UnhookWindowsHookEx Lib "user32" _
(ByVal hHook As Long) As Long
Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, _
ByVal ncode As Long, ByVal wParam As Long, lParam As Any) As Long
Public hnexthookproc As Long
Public Const HC_ACTION = 0
Public Const WH_KEYBOARD = 2
Public Sub UnHookKBD()
If hnexthookproc <> 0 Then
UnhookWindowsHookEx hnexthookproc
hnexthookproc = 0
End If
End Sub
Public Function EnableKBDHook()
If hnexthookproc <> 0 Then
Exit Function
End If
hnexthookproc = SetWindowsHookEx(WH_KEYBOARD, AddressOf _
MyKBHFunc, App.hInstance, App.ThreadID)
If hnexthookproc <> 0 Then
EnableKBDHook = hnexthookproc
End If
End Function
Public Function MyKBHFunc(ByVal iCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
If wParam = 13 And iCode = 0 And lParam > 0 Then
Debug.Print "按了回车键"'这里就捕捉到回车键按下的信息,你可以在这里写代码触发你的按钮事件
End If
Call CallNextHookEx(hnexthookproc, iCode, wParam, lParam)
End Function
'以下是窗口中的代码
Private Sub Form_Load()
Call EnableKBDHook
End Sub
Private Sub Form_Unload(Cancel As Integer)
Call UnHookKBD
End Sub
Public Sub InputNumeric(KeyAscii As Integer, txtItem As TextBox)
Select Case KeyAscii
Case Asc("-") '允许负数
If txtItem.SelStart = 0 Then
If Left(txtItem.Text, 1) = "-" Then
KeyAscii = 0
Beep
End If
Else
KeyAscii = 0
Beep
End If
Case 8
'无变化,退格键不屏蔽
Case Asc(" ") '32
If txtItem.SelLength = 0 Then
KeyAscii = 0
End If
Case Asc(".") '46 '允许小数点
If InStr(txtItem.Text, ".") Then
KeyAscii = 0
End If
Case Is < Asc(0) '48
KeyAscii = 0
Case Is > Asc(9) '57
KeyAscii = 0
End Select
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
newstyle = SetWindowLong(NumberText.hwnd, GWL_STYLE, curstyle)
NumberText.Refresh
End Sub
Private Sub Form_Load()
SetNumber Text1, True
End Sub