[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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

[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.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.