2014-06-12 27 views
0

我正在構建一個c#win窗體應用程序。應用程序讀取IRC頻道並顯示正在經歷的消息。這些消息顯示等:Windows窗體RichTextBox - 點擊單詞驅動的事件

{用戶名}:{消息張貼或動作進行}

我需要它使得應用程序的用戶可以在用戶名單擊(這些都存儲在數組等都可以被引用)另一種模式形式打開,用戶名傳入。麻煩的是,我不知道如何檢測RichTextBox中的哪個單詞被點擊(或者即使這是可能的)。

任何幫助將不勝感激。我真的處於死衚衕,除了檢測高亮選擇的代碼外,我不在哪裏。

的問候, 克里斯

+0

我發現了幾個例子,看起來像這樣:http://blog.csharphelper.com/2012/01/02/find-the-word-under-the-mouse-in-a-richtextbox-control-在-c.aspx。它們似乎都是對文本的暴力搜索,因爲RichTextBox不支持這種類型。 – DonBoitnott

回答

2

我所能找到的唯一解決方案是使用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。

+0

非常好,謝謝奧斯汀。這是一種魅力。 –

相關問題