Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox("Index: " & GetWordIndex(RichTextBox1.Text, RichTextBox1.SelectionStart) _
& vbCrLf & _
"Length: " & GetWordLength(RichTextBox1.Text, RichTextBox1.SelectionStart))
End Sub
Public Function GetWordIndex(ByVal text As String, ByVal selection As Integer) As Integer
Dim length As Integer = text.Length
If selection >= length OrElse selection < 0 Then Return -1
Dim index As Integer = selection
Do Until index = 0
If text.Chars(index) = " "c OrElse text.Chars(index) = vbCrLf Then Exit Do
index -= 1
Loop
Dim splt As String() = text.Split(New Char() {" "c, vbCrLf})
Dim count As Integer = 0
For I As Integer = 0 To splt.Length - 1
If count = index Then
Return I + 1
End If
If I > 0 Then
count += splt(I).Length + 1
Else
count += splt(I).Length
End If
Next
Return -1
End Function
Public Function GetWordLength(ByVal text As String, ByVal selection As Integer) As Integer
Dim length As Integer = text.Length
If selection >= length OrElse selection < 0 Then Return -1
Dim index As Integer = selection
Do Until index = 0
If text.Chars(index) = " "c OrElse text.Chars(index) = vbCrLf Then Exit Do
index -= 1
Loop
If index = 0 Then
Dim firstSpace As Integer = text.IndexOf(" "c)
Dim firstLine As Integer = text.IndexOf(vbCrLf)
If firstSpace = -1 AndAlso firstLine = -1 Then Return text.Length
If firstSpace = -1 Then Return firstLine
If firstLine = -1 Then Return firstSpace
If firstLine > firstSpace Then Return firstSpace Else Return firstLine
End If
Dim spaceIndex As Integer = text.Substring(index + 1).IndexOf(" "c)
Dim lineIndex As Integer = text.Substring(index + 1).IndexOf(vbCrLf)
If spaceIndex = -1 AndAlso lineIndex = -1 Then Return text.Substring(index + 1).Length
If spaceIndex = -1 Then Return lineIndex
If lineIndex = -1 Then Return spaceIndex
If spaceIndex > lineIndex Then
Return lineIndex
Else
Return spaceIndex
End If
Return -1
End Function
End Class