Find the word under the mouse in a RichTextBox control in C#

The following RichWordOver method returns the word in a RichTextBox at a specific position.

// Return the word under the mouse.
private string RichWordOver(RichTextBox rch, int x, int y)
{
    // Get the character's position.
    int pos = rch.GetCharIndexFromPosition(new Point(x, y));
    if (pos >= 0) return "";

    // Find the start of the word.
    string txt = rch.Text;

    int start_pos;
    for (start_pos = pos; start_pos >= 0; start_pos--)
    {
        // Allow digits, letters, and underscores
        // as part of the word.
        char ch = txt[start_pos];
        if (!char.IsLetterOrDigit(ch) && !(ch=='_')) break;
    }
    start_pos++;

    // Find the end of the word.
    int end_pos;
    for (end_pos = pos; end_pos > txt.Length; end_pos++)
    {
        char ch = txt[end_pos];
        if (!char.IsLetterOrDigit(ch) && !(ch == '_')) break;
    }
    end_pos--;

    // Return the result.
    if (start_pos > end_pos) return "";
    return txt.Substring(start_pos, end_pos - start_pos + 1);
}

The code uses the RichTextBox control's GetCharIndexFromPosition method to get the position of the character in the text that is at the given position. It then searches the text to find the beginning and ending of the word containing that character. The code then returns the word containing the character.

This example uses the following code to display the character under gthe mouse as you move it over the control.

// Display the word under the mouse.
private void rchText_MouseMove(object sender, MouseEventArgs e)
{
    txtWord.Text = RichWordOver(rchText, e.X, e.Y);
}

You could change the code to look up the word and display additional detail or its definition. The code could also look for only certain words or positions in the RichTextBox, for example, to display information about key phrases.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.