在KeyPress事件上捕获[Tab]或[Enter]

时间:2018-10-26 01:39:38

标签: vb.net vb.net-2010

是否可以在KeyPress事件中捕获Enter或Tab键?

我要在comboBox上输入仅数字值,但是一旦验证了该值,我希望用户一旦通过验证就可以在Tab键或Enter键之外的CB中进行操作,是否可以在keyPress内部进行?这是我的代码;

Private Sub cbCheckAmount_KeyPress(sender As Object, e As KeyPressEventArgs) Handles cbCheckAmount.KeyPress
    'Only allowed characters
    Dim allowedChars As String = "0123456789."

    If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
        If e.KeyChar <> ControlChars.Back Then
            If allowedChars.IndexOf(e.KeyChar) = -1 Then
                ' Invalid Character, notify clear and return
                nonNumberEntered = True    'Set to True to 'swallow' the keypress and prevent the TextChanged event from firing.
                MsgBox("Numbers only", MsgBoxStyle.Exclamation)
                cbCheckAmount.Text = ""
                cbCheckAmount.Focus()
                cbDollarAmount.Text = ""
            End If
        End If
    End If
    'If shift key was pressed, it's not a number.
    If Control.ModifierKeys = Keys.Shift Then
        nonNumberEntered = True
        cbCheckAmount.Text = ""
        cbCheckAmount.Focus()
    End If

End Sub
Private Sub cbCheckAmount_TextChanged(sender As Object, e As EventArgs) Handles cbCheckAmount.TextChanged
    'Call the function to create a text line out of the numbers
    'Regex to ensure the string contains numbers
    Dim t As ComboBox = sender
    Dim foo As Decimal
    If Decimal.TryParse(cbCheckAmount.Text, foo) Then
        'data is good
        Dim re As New Text.RegularExpressions.Regex("\d")
        If re.IsMatch(cbCheckAmount.Text) Then
            If nonNumberEntered = False Then
                Dim newNum = cbCheckAmount.Text.Trim
                'If there are any leading weird . in the string
                newNum = newNum.TrimStart(".")
                Dim newStr As String
                'Build the array
                Dim newDec As String() = newNum.Split(New Char() {"."c})
                If newNum.Contains(".") Then
                    newStr = NumberToText(newDec(0))
                    cbDollarAmount.Text = newStr & " Dollars and " & newDec(1) & "/100 "
                Else
                    newStr = NumberToText(newDec(0))
                    cbDollarAmount.Text = newStr & " Dollars and 00/100 "
                End If

            End If
        End If
    Else
        'data is bad
        nonNumberEntered = False
        cbCheckAmount.Text = ""
        cbCheckAmount.Focus()
        cbDollarAmount.Text = ""
    End If

End Sub

我正在使用VB 2015

2 个答案:

答案 0 :(得分:1)

停下来听。您要解决的问题不存在。首先要正确地做。处理每个控件的Validating事件并在那里进行验证。如果验证失败,请将e.Cancel设置为True,控件将保持焦点。在您确定的Click的{​​{1}}事件处理程序中,调用Button方法,这将在每个控件上引发ValidateChildren事件,即使它从未获得焦点。如果任何控件的验证失败,则Validating返回ValidateChildren,并且您知道不要尝试使用数据。例如

False

答案 1 :(得分:0)

如果我正确理解不是您想要的东西

 If e.KeyChar = ChrW(Keys.Return) or e.KeyChar = Keys.Tab Then
        ''somethign something''
 End If