在KeyDown上捕获keys.TAB

时间:2013-08-06 17:52:58

标签: vb.net tabs keydown onkeydown

我正在尝试在Keydown事件上捕获TAB按键。 我可以在How to fire an event when the tab key is pressed in a textbox?

上看到另一篇文章

但是,在上面的链接中,发布的解决方案对我来说不起作用,我在下面提到过。

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) _
                         Handles TextBox1.KeyDown
    If e.KeyCode = Keys.Tab Then
       e.SuppressKeyPress = True
       'do something
    End If
End Sub

出于测试目的,我在FORM1上添加了2个简单的文本框,并编写下面的代码来捕获KeyDown事件上的TAB。

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    If e.KeyCode = Keys.Tab Then
        e.SuppressKeyPress = True
        MsgBox("TAB DOWN")
    End If
End Sub

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Me.Text = e.KeyChar
End Sub

Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
    If e.KeyCode = Keys.Tab Then
        MsgBox("TAB UP")
    End If
End Sub

Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
    Me.Text = "LEAVE"
End Sub

上面的代码应该假设在按下TAB时在KeyDown上显示一个消息框。它不起作用。

请让我知道我做错了什么。 在此先感谢!!!

2 个答案:

答案 0 :(得分:7)

我发现了一个名为PreviewKeyDown()的新事件

 Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    If e.KeyCode = Keys.Tab Then
        Me.Text = "TAB Capture From TextBox1_KeyDown At " & Now.ToString
    End If
End Sub

Private Sub TextBox1_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles TextBox1.PreviewKeyDown
    If e.KeyCode = Keys.Tab Then
        Me.Text = "TAB Capture From TextBox1_PreviewKeyDown At " & Now.ToString
    End If
End Sub

如果您将执行上述代码,您将能够在PreviewKeyDown()事件中捕获TAB键。

答案 1 :(得分:-2)

MsgBox()是VB6的延续,您应该使用消息框的.NET实现,如下所示:

MessageBox.Show("TAB UP")

此外,当我打算设置文本框的Text属性时,您正在针对表单类(Me)的实例设置Text属性,如这样:

Me.TextBox1.Text = e.KeyChar