简体   繁体   中英

How to move the caret to the beginning of a multiline textbox?

I have a text box in windows forms which is set to Multiline. I have a KeyDown event handler which recognizes the Enter key in the textbox and does something and then clears the text from the textbox. How can I move the caret to the beginning of textbox programmatically? I can see it when I press Ctrl + Home in the textbox. I tried the below using SelectionStart property but it leaves the cursor at the beginning of second line.

Private Sub txtComments_KeyDown(sender As Object, e As KeyEventArgs) Handles txtComments.KeyDown
    If e.KeyCode = Keys.Enter Then
        If txtComments.TextLength > 0 Then
            AddSelection(txtComments.Text)
            txtComments.Clear()
        End If

        If txtComments.TextLength = 0 Then
            txtComments.Focus()
            txtComments.SelectionStart = 0
        End If

    End If
End Sub

The issue is because you're clearing the control and focussing at the start of the control before the actual KeyPress event is handled by the underlying control, so pressing Enter still adds a new line to the control after all your code has run, which is why you end up on the second line.

You can prevent this behaviour by using the SuppressKeyPress property of the KeyEventArgs passed in to your event handler:

Private Sub txtComments_KeyDown(sender As Object, e As KeyEventArgs) Handles txtComments.KeyDown
    If e.KeyCode = Keys.Enter Then
        If txtComments.TextLength > 0 Then
            AddSelection(txtComments.Text)
            txtComments.Clear()
            e.SuppressKeyPress = True
        End If
    End If
End Sub

The documentation for this property says:

Gets or sets a value indicating whether the key event should be passed on to the underlying control.

and:

You can assign true to this property in an event handler such as KeyDown in order to prevent user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM