Capture keys.TAB on KeyDown

Kartik Goyal picture Kartik Goyal · Aug 6, 2013 · Viewed 23.9k times · Source

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!!!

Answer

Kartik Goyal picture Kartik Goyal · Aug 27, 2013

I found a new event called 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

If you will execute the above code, you will able to capture TAB key on PreviewKeyDown() event.