TX Text Control Source Code Library

Getting the word at the current mouse position

Sometimes, it is necessary to know the word at the current mouse position, in order to display additional information to the end-user.

This sample displays a tool tip with the word's text when the end-user moves the mouse over a word.

The function GetWordFromIndex must be called with the character index and returns the complete word at this position. To avoid a potential flicker that is caused by changing the input position, this sample does not use the Find method to search for the word delimiters like a comma, period or any other punctuation marks.

Instead of the Find method, the function uses the internal .NET String methods IndexOfAny and LastIndexOfAny. These methods return an index of a specific character. The SubString method is used to build the detected word from the complete document's text.

private string GetWordFromIndex(int Index) { string CompleteText = textControl1.Text.Replace("\r\n","\n"); Char[] chars = new Char[] { ',', ';', ':', '!', '?', '.', ' ', (char)9, (char)10 }; int lastChar = CompleteText.IndexOfAny(chars, Index); if(lastChar != -1) CompleteText = CompleteText.Substring(0, lastChar); int firstChar = CompleteText.LastIndexOfAny(chars); return CompleteText.Substring(firstChar + 1); }

The above function is called in TX Text Control's MouseMove event. The GetItem method of the TextChars collection of TX Text Control returns the character index of a specific location. This method is called with the return value of the MouseMove event. The return value of the GetWordFromIndex function is used to display a tool tip above the specific word.

This approach has the advantage that the current input position must not be changed.

private void textControl1_MouseMove(object sender, MouseEventArgs e) { int charIndex = textControl1.TextChars.GetItem(e.Location, true).Number; string currentWord = GetWordFromIndex(charIndex); if (currentWord != "") { toolTip1.ToolTipTitle = currentWord; toolTip1.Show("Index: " + charIndex.ToString(), this, e.X + 20, e.Y - 10); } else toolTip1.Hide(this); }

The sample requires Visual Studio 2005 and at least a trial version of TX Text Control .NET for Windows Forms 13.0.

 
 

Products

Support

Downloads

Corporate

Buy Now