例程添加1个字符后,游标不在文本末尾

时间:2016-02-10 07:38:15

标签: vb.net

我在vb.net的文本框中键入了几个字母,然后点击向上箭头。这会在文本框中添加重音e,但光标不在文本末尾。

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As   System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

    If e.KeyCode = Keys.Up Then
        MessageBox.Show("Up arrow key")
        TextBox1.Text = TextBox1.Text & "é"
        TextBox1.SelectionStart = TextBox1.Text.Length + 1

    End If

End Sub

1 个答案:

答案 0 :(得分:0)

这是一种非常奇怪的行为,但似乎vb.net在TextBox1_KeyDown完成之前没有更新位置。

在我提出更好的建议之前,我的建议是启动计时器并更新Timer中的SelectionStart。

    Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

        If e.KeyCode = Keys.Up Then
            MessageBox.Show("Up arrow key")
            TextBox1.Text = TextBox1.Text & "é"
            Timer1.Start()
        End If

    End Sub

  Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Timer1.Stop()
        TextBox1.SelectionStart = TextBox1.Text.Length
    End Sub

顺便说一句,你不需要TextBox1.SelectionStart = TextBox1.Text.Length + 1

中的+1