Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

MsgBox() is a holdover from VB6 and you should use the .NET implementation of a message box, like this:

MessageBox.Show("TAB UP")

Also, you are setting a Text property against the instance of the form class (Me), when I think you intend to set the Text property of the text box, like this:

Me.TextBox1.Text = e.KeyChar
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top