我所能找到的唯一解決方案是使用RichTextBox的方法GetCharIndexFromPosition,然後從那裏向外進行一個循環,在每一端的任何非字母停止。
private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
{
int index = richTextBox1.GetCharIndexFromPosition(e.Location);
String toSearch = richTextBox1.Text;
int leftIndex = index;
while (leftIndex < toSearch.Count() && !Char.IsLetter(toSearch[leftIndex]))
leftIndex++; // finds the closest word to the right
if (leftIndex < toSearch.Count()) // did not click into whitespace at the end
{
while (leftIndex > 0 && Char.IsLetter(toSearch[leftIndex - 1]))
leftIndex--;
int rightIndex = index;
while (rightIndex < toSearch.Count() - 1 && Char.IsLetter(toSearch[rightIndex + 1]))
rightIndex++;
String word = toSearch.Substring(leftIndex, rightIndex - leftIndex + 1);
MessageBox.Show(word);
}
}
在你的情況下,你可能會有數字或空格的用戶名,並且可能希望在遇到冒號時停止rightIndex。如果用戶名始終位於換行符的開頭,那麼您可能還想要在換行符('\ n')處停止leftIndex。
我發現了幾個例子,看起來像這樣:http://blog.csharphelper.com/2012/01/02/find-the-word-under-the-mouse-in-a-richtextbox-control-在-c.aspx。它們似乎都是對文本的暴力搜索,因爲RichTextBox不支持這種類型。 – DonBoitnott