Tuesday, April 1, 2008

Stupid System.Windows.Form.ToolTip()

Last week I updated some legacy code (don't we all love that?). Updating the actual code was pretty straightforward, but I decided to add some visual elements to notify the user of validation issues.
To make a long story short, I decided to popup a ToolTip() whenever a user tabs away from a control and a validation error is raised.

1 private void textBox1_Leave(object sender, EventArgs e)
2 {
3 // create new tooltip
4 ToolTip tt = new ToolTip()
5 {
6 Active = true,
7 IsBalloon = true,
8 ToolTipIcon = ToolTipIcon.Info,
9 ToolTipTitle = "Test",
10 InitialDelay = 0
11 };
12
13 // associate tooltip with control
14 tt.SetToolTip(textBox1, "Test");
15
16 // show the tooltip
17 tt.Show("Stupid", textBox1, 3000);
18 }


Now this code (which I've simplified to illustrate) seems to work fine, but there's a snag. If the mouse cursor hovers above the control when the ToolTip() is displayed for that control, the ToolTip() stem points to the wrong location.


stupidtt


Move the mouse cursor away from the control, tab to the next control and it will point to the control you have specified. Google didn't really help. Some mentioning of the issue, but vary vague and non-specific.


So in the end, I resorted to writing a (static) class to determine whether the mouse cursor is above the control which will receive the ToolTip(), move the mouse away from the control and back again after the ToolTip() has been displayed (hiding the cursor doesn't work... I've tried). Not really elegant, but it works.



1 // move mouse if mouse is over control, and show tooltip. else just show tooltip
2 if (m.OverControl(control))
3 {
4 m.MoveAway(control);
5
6 // associate tooltip with control
7 tt.SetToolTip(textBox1, "Test");
8
9 // show the tooltip
10 tt.Show("Stupid", textBox1, 3000);
11
12 m.MoveBack();
13 }
14


Maybe someone has encountered the same problem? Maybe there's a better solution?


Environment:
Microsoft ® Visual Studio 2008
Microsoft ® .NET framework 3.5
Microsoft ® Windows XP (SP2)

0 comments: