Title: Find the word under the mouse in a RichTextBox control in C#
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;
}
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 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 the example to experiment with it and to see additional details.
|