Chris Felstead
Chris Felstead

Reputation: 1208

Windows Forms RichTextBox - Event driven by the word clicked on

I am building a c# win forms application. The application reads an IRC channel and displays the messages that are going through. These messages are displayed like:

{username}: {message that posted or action performed}

I need it so that the user of an application can click on a username (these are stored in array and so can be referenced) another modal form opens with the username passed in. The trouble is, I have no idea how to detect which word in the RichTextBox was clicked on (or even if that is possible).

Any help will be greatly appreciated. I really am at a dead end and other than code that detects a highlighted selection I am no where.

Regards, Chris

Upvotes: 0

Views: 539

Answers (1)

Austin Heller
Austin Heller

Reputation: 320

The only solution I could find is to use the RichTextBox method GetCharIndexFromPosition and then perform a loop outward from there, stopping at each end for anything non-alphabetic.

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);
    }
}

In your situation, you may have usernames with numbers or spaces and might want to stop the rightIndex when it hits a colon. If the username is always at the start of a newline, you may also want to stop the leftIndex at newlines ('\n').

Upvotes: 3

Related Questions