5

I am trying to capture TAB keypress on Keydown Event. I can see another post on How to fire an event when the tab key is pressed in a textbox?

However, On the above link, posted solution is not working for me which I mentioned below.

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

For the testing purpose, I have added 2 simple textboxes on FORM1 and write the below code to capture the TAB on KeyDown event.

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

My above code should suppose to display a message box on KeyDown when TAB is press. It's not working.

Please let me know what I am doing wrong. Thanks in advance!!!

4

2 回答 2

9

我发现了一个名为 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 键。

于 2013-08-27T05:34:11.497 回答
-2

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

MessageBox.Show("TAB UP")

此外,当我认为您打算设置文本框的属性时,您正在Text针对表单类 ( ) 的实例设置属性,如下所示:MeText

Me.TextBox1.Text = e.KeyChar
于 2013-08-06T18:30:01.110 回答