Andy Langowitz
2003-12-05 14:21:48 UTC
I'm looking for a way to have a "Word ToolTip" feature in
a TextBox or RichTextBox.
That is, for example, hover (NOT select) the mouse over
a word and see that word's definition right next to the
word.
Couldn't resist spending a half hour preparing an answer to this one. I'ma TextBox or RichTextBox.
That is, for example, hover (NOT select) the mouse over
a word and see that word's definition right next to the
word.
not sure how far back to start, so I'm going to assume you know nothing
and take it one step at a time. If you'd like to try it out as you go,
open a new C# Windows Application project and drop a RichTextBox control
on your Form.
Q: How do I add tool tip functionality to a RichTextBox?
A: Drop a ToolTip control onto your form, and a new property will appear
in the property sheet of the RichTextBox for tooltip text.
Q: How do I change the text of the tooltip at runtime?
A: Invoke the SetToolTip method on the tooltip control, passing it the
RichTextBox as the first argument, and the tooltip text as the second
argument. Example:
string sToolTip = "here is some text set at runtime";
toolTip1.SetToolTip(richTextBox1, sToolTip);
Q: How do I make the text of the tooltip dependent on the mouse position
within the RichTextBox?
A: Add a handler for the MouseMove event of the RichTextBox and call the
SetToolTip method from there. (In your case, this code should extract the
word at the event's mouse position from the RichTextBox and look up the
definition, but I'm getting to that). Example:
private void richTextBox1_MouseMove(object sender,
System.Windows.Forms.MouseEventArgs e)
{
string sTip = String.Format ("X={0}, Y={1}", e.X, e.Y);
toolTip1.SetToolTip(richTextBox1, sTip);
}
Q: How do I determine at what index in the text the current mouse position
is?
A: Call the GetCharIndexFromPosition method of the RichTextBox. Example:
richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y));
Q: How do I extract a word from the text at a given index?
A: Now we're down to basic string manipulation. Here is my final code,
including a helper function to extract a word from the text (you will
probably want additional separators):
private void richTextBox1_MouseMove(object sender,
System.Windows.Forms.MouseEventArgs e)
{
string sTip = ExtractWord (richTextBox1.Text,
richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y)));
toolTip1.SetToolTip(richTextBox1, sTip);
}
private static char[] s_acSeparators = {' ', '\n'};
private string ExtractWord (string sText, int iPos)
{
//get the position of the beginning of the word (if no separator
found, this gives zero)
int iStart = sText.LastIndexOfAny(s_acSeparators, iPos) + 1;
//get the position of the separator after the word
int iEnd = sText.IndexOfAny(s_acSeparators, iPos);
if (iEnd < 0)
iEnd = sText.Length;
if (iEnd < iStart)
return "";
return sText.Substring(iStart, iEnd - iStart);
}
Now all you need to do is look up the word in your dictionary.
HTH,
Andy Langowitz