为了显示TreeNodes
的工具提示,不需要ToolTip
控件。 TreeView
有一个属性ShowNodeToolTips
,您可以设置为true
和TreeNodes
有一个ToolTipText
属性。
但是,如果要将ToolTip
显示为气球,事情会变得更加复杂。幸运的是TreeView
有一个NodeMouseHover
事件。与Timer
一起,我们可以使ToolTip
按预期运行。
在我们的形式,我们做出这些声明并设置定时器事件处理程序
private const int InitialToolTipDelay = 500, MaxToolTipDisplayTime = 2000;
private ToolTip toolTip = new ToolTip();
private Timer timer = new Timer();
private TreeNode toolTipNode;
public frmTreeViewWithToolTip()
{
InitializeComponent();
toolTip.IsBalloon = true;
timer.Tick += new EventHandler(timer_Tick);
}
在NodeMouseHover
我们启动这一进程
private void treeView_NodeMouseHover(object sender,
TreeNodeMouseHoverEventArgs e)
{
timer.Stop();
toolTip.Hide(this);
toolTipNode = e.Node;
timer.Interval = InitialToolTipDelay;
timer.Start();
}
定时器将两次启动:初始延迟一次并且一次用于气球的最大显示时间。因此,我们必须在timer.Tick
事件处理程序处理这两种情况
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
if (timer.Interval == InitialToolTipDelay) {
Point mousePos = treeView.PointToClient(MousePosition);
// Show the ToolTip if the mouse is still over the same node.
if (toolTipNode.Bounds.Contains(mousePos)) {
// Node location in treeView coordinates.
Point loc = toolTipNode.Bounds.Location;
// Node location in form client coordinates.
loc.Offset(treeView.Location);
// Make balloon point to upper right corner of the node.
loc.Offset(toolTipNode.Bounds.Width - 7, -12);
toolTip.Show("Node: " + toolTipNode.Text, this, loc);
timer.Interval = MaxToolTipDisplayTime;
timer.Start();
}
} else {
// Maximium ToolTip display time exceeded.
toolTip.Hide(this);
}
}
最后,我们不希望显示ToolTip
如果鼠标离开TreeView
private void treeView_MouseLeave(object sender, EventArgs e)
{
timer.Stop();
toolTip.Hide(this);
}
它工作的很好,我还有一个问题是有没有任何机会来定制这个工具提示的外观(像气球一样)。谢谢你的回答。 – santBart 2012-04-06 13:13:24
我的初步答案只有在需要标准工具提示时才有用。我添加并测试了一个解决方案,它创建气球工具提示,以适当的方式延迟它们,并将它们显示在相关“TreeNode”相对方便的位置。 – 2012-04-06 15:39:18
查看“ToolTip”的属性。您可以更改颜色,更改字体,设置标题和图标等等。如果将属性'OwnerDraw'设置为'true',则可以在'ToolTip.Draw'事件处理程序中自行绘制'ToolTip'(仅在IsBalloon == false时起作用)。 – 2012-04-06 15:46:28