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

[word under the mouse]

The following WordUnderMouse method returns the word under the mouse in a RichTextBox.

// Return the word under the mouse.
private string WordUnderMouse(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;

    // 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;

    // 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 that is at the given mouse 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 the mouse as you move it over the control.

// Display the word under the mouse.
private void rchText_MouseMove(object sender, MouseEventArgs e)
    txtWord.Text = WordUnderMouse(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.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in controls, miscellany and tagged , , , , , , , , , , , . Bookmark the permalink.

11 Responses to Find the word under the mouse in a RichTextBox control in C#

  1. Art says:

    Hi. This is a good post. But what about to get text form pdf, word or any other place from desktop. Can you help me with this please? Thanks.

  2. Rod Stephens says:

    Sorry but that’s going to be hard. You could probably write a VBA macro in Word to track the mouse position but in general you’ll have trouble figuring out what words are displayed where in another program.

    You can track the mouse and use the WindowFromPoint API function to see what window is under that position. See the example:

    But then you would need to be able to peek into that program to see what it was displaying and where.

    This example contains the RichTextBox so its (relatively) easy for the program to figure out what word is where. In general I don’t think there’s a reasonable way to figure out what word is under the mouse in some other program. (You could grab an image of the program and look at it. I suppose you could try text recognition. Sounds really hard.)

  3. Aang Kurts says:

    Thank you for your code. I am new to Windows Forms and this helped me.
    There was some problem with the code, here are my changes to make it work:

    // Allow digits, letters, and underscores
    // as part of the word.
    private static bool AcceptChar(char c) {
        return char.IsLetterOrDigit(c) || c == '_';
    // Return the word under the mouse.
    private static string WordUnderMouse(TextBoxBase rch, int x, int y)
        // Get the character's position.
        int pos = rch.GetCharIndexFromPosition(new Point(x, y));
        if (pos = 0 && AcceptChar(txt[startPos]); startPos--) { }
        // Find the end of the word.
        int endPos;
        for (endPos = pos; endPos  endPos ? "" : txt.Substring(startPos, endPos - startPos + 1);
    • RodStephens says:

      I think there’s something wrong with your code as it was entered because it contains syntax errors. Probably WordPress messed up some of the characters that you typed so that code shouldn’t work. For example, “if (pos = 0” doesn’t make sense because = is assignment and == is comparison.

      Can you check the code again?

      • wssdf says:

        Two wrongs I found And cleared it
        1- ‘If pos >= 0 Then
        ‘ Return “”
        ‘End If
        I made comment it

        2- Do while end_pos > txt.Length
        correct is : Do Until end_pos > txt.Length

        • RodStephens says:

          1. The documentation for the RichTextBox’s GetCharIndexFromPosition method implies that it may return -1 if it cannot find a character at the given position. I can’t seem to make it happen, but if it did, the program would crash. I would leave this test in just to be safe, although you’re right that you can probably remove it.

          2. Your code looks like Visual Basic. There is no “do while” in this example because it’s C#. In this example the code is:

          for (end_pos = pos; end_pos < txt.Length; end_pos++)

          I believe that is correct. If you want to use a while/until loop, I think you might want "do while end_pos < txt.Length". That way the program will check the value before it enters the loop, so it won't execute if end_pos starts out >= txt.Length.

          But again, that may not be an issue if GetCharIndexFromPosition doesn't return weird character indices.

  4. Nivas Patil, Pune says:

    hiiii… everybody…
    i am trying English word spell check program in c#. i am using richTexbox. while typing display word suggestion. and my code is of richTextBox1.Text.LastOrDefault(); so i can search word, who word last of richtextbox. but not displayed suggestion box when i typing anywhere into richtextbox.
    i have one or more line and i am trying add more word into matter, then that not will be LastOrDefault so not displayed suggestion. i want displayed suggestion box, when i will be typing word to any where into richtexbox. so pls who can help for this solution.

    • RodStephens says:

      You might be able to display a context menu, but that might take focus so the user couldn’t type any more. I think you would need to make it appear above the RichTextBox without taking focus.

      Or you might display suggestions in a list below so the user could pick one. My phone does that as I type.

  5. Xam says:

    Nice post. I only want to point out a mistake. In the second for loop it should be: end_pos <= txt.Length, otherwise it will never enter in the bucle.

    • RodStephens says:

      I think the code is correct. Remember that the character indices start at 0, so the last character has index txt.Length - 1. If you use <= in the second loop, the program crashes when it tries to look at txt[txt.Length].

  6. Sam Kim says:

    Two lines to change so it works:

    if (pos >= 0) return “”;
    ==> if (pos txt.Length; end_pos++)
    ==> for (end_pos = pos; end_pos < txt.Length; end_pos++)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.