我正在尝试捕获 Keydown 事件上的 TAB 按键。 我可以看到另一篇文章如何在文本框中按下 Tab 键时触发事件?
但是,在上面的链接上,发布的解决方案对我不起作用,我在下面提到。
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 上显示一个消息框。没用。
请让我知道我做错了什么。 预先感谢!
我发现了一个名为 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 键。
Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) 处理 Textbox1.KeyPress 如果 e.KeyChar = Chr(13) 那么 Me.Textbox2.Focus() 万一 结束子
Private Sub Textbox1_KeyDown(sender As Object, e As KeyEventArgs) Handles Textbox1.KeyDown
If e.KeyCode = 13 Then
Textbox2.Focus()
End If
End Sub
MsgBox()
是 VB6 的遗留物,您应该使用消息框的 .NET 实现,如下所示:
MessageBox.Show("TAB UP")
此外,当我认为您打算设置文本框的
Text
属性时,您正在针对表单类(Me
)的实例设置 Text
属性,如下所示:
Me.TextBox1.Text = e.KeyChar