爲了顯示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