Я пытался создать программу, которая найдет слово, на которое щелкнул пользователь, в многострочном текстовом поле. Эта процедура основана на индексе с позиции клика. Код, который я реализовал:
Public Class Form1
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
'Try
Dim indexClicked As Integer = TextBox1.GetCharIndexFromPosition(New Point(e.X, e.Y))
Dim ch As Char = TextBox1.Text.Chars(indexClicked)
Dim indexOfWord As Int32
If Not ch = " " Then
Dim wordFound As Boolean
Dim previousCh As Char
Dim previousIndex As Integer = indexClicked
While Not wordFound
previousIndex = previousIndex - 1
previousCh = TextBox1.Text.Chars(previousIndex)
If previousCh = " " Then
indexOfWord = previousIndex + 1
wordFound = True
End If
End While
Else
indexOfWord = indexClicked + 1
End If
Label1.Text = indexClicked & ", " & indexOfWord
Label2.Text = GetWordByIndex(TextBox1.Text, indexOfWord)
' Catch ex As Exception
' Label2.Text = ex.Message
' End Try
End If
End Sub
Public Shared Function GetWordByIndex(input As String, index As Integer) As String
Try
Dim words = input.Split(" ")
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
Return words(index)
Catch ex As Exception
'handle the exception your way
Return String.Empty
End Try
End Function
End Class
Проблема в том, что всякий раз, когда программа достигает строки:
previousCh = TextBox1.Text.Chars(previousIndex)
он выходит с:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication1.exe
Additional information: Index was outside the bounds of the array.
Пока выдается исключение, при наведении курсора на переменную previousIndex Visual Studio показывает мне ее значение: -1.
Я думаю, что условие previousCh = " "
никогда не выполняется, поэтому программа никогда не выходит из цикла while, который продолжает искать предыдущий символ. В какой-то момент int previousIndex становится отрицательным, и программа вылетает. Почему условие не работает должным образом?
В чем проблема? Спасибо.