.netwinformstextboxtextselectiontext-cursor

Get text from textbox in cursor position .net


I need to get text from a textbox in winforms, i need to get the text that the cursor is in between e.g

Hello or posit|ion or look

This should return the word position (Note here i used the pipe as the cursor)

Do you know any technique i can use for this


Solution

  • I tested this real quick and it seems like it works consistently

    Private Function GetCurrentWord(ByRef txtbox As TextBox) As String
        Dim CurrentPos As Integer = txtbox.SelectionStart
        Dim StartPos As Integer = CurrentPos
        Dim EndPos As Integer = txtbox.Text.ToString.IndexOf(" ", StartPos)
    
        If EndPos < 0 Then
            EndPos = txtbox.Text.Length
        End If
    
        If StartPos = txtbox.Text.Length Then
            Return ""
        End If
    
        StartPos = txtbox.Text.LastIndexOf(" ", CurrentPos)
        If StartPos < 0 Then
            StartPos = 0
        End If
    
        Return txtbox.Text.Substring(StartPos, EndPos - StartPos).Trim
    End Function