如何在输入键按下时将光标跳转到下一个文本框

时间:2016-06-17 20:31:44

标签: .net vb.net winforms

这里我根据按钮点击动态创建了文本框

因此,当我将光标放在第一个文本框中时,当我按下确定按钮时,它应该跳转到下一个文本框。我怎么能这样做

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim count As Integer
        Dim textbox As New TextBox()
        count = Panel1.Controls.OfType(Of TextBox)().ToList().Count
        textbox.Location = New System.Drawing.Point(60, 25 * count)
        textbox.Size = New System.Drawing.Size(80, 20)
        textbox.Name = "textbox_" & (count + 1)
        Panel1.Controls.Add(textbox)
    End Sub

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以处理TextBox控件的KeyDown事件并检查是否 Enter ,选择下一个控件:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For i As Integer = 1 To 10
        Dim txt = New TextBox()
        txt.Name = String.Format("textbox_{0}", i)
        AddHandler txt.KeyDown, AddressOf txt_KeyDown
        Me.FlowLayoutPanel1.Controls.Add(txt)
    Next
End Sub

Private Sub txt_KeyDown(sender As Object, e As KeyEventArgs)
    If (e.KeyData = Keys.Enter) Then
        e.Handled = True
        SendKeys.Send("{Tab}")
    End If
End Sub

注意:

  • 最好使用TableLayoutPanelFlowLayoutPanel添加动态控件。

  • 添加处理程序也可以这样做:

    AddHandler txt.KeyDown, Sub(s, ea)
                                If (ea.KeyData = Keys.Enter) Then
                                    ea.Handled = True
                                    SendKeys.Send("{Tab}")
                                End If
                            End Sub